如何检查列表中第一个元组的第一个字母?

2024-03-28 20:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这样的东西

userPassList=[('*username','password'),('username2','password2'),('username3','password3')]

我想在列表中搜索第一个字符是*的用户名。在

我在想:

^{pr2}$

但这并不完全正确。有什么想法或建议吗?在

编辑:我没有密码,只有用户名。在


Tags: 编辑密码列表usernamepassword字符建议用户名
1条回答
网友
1楼 · 发布于 2024-03-28 20:14:44

这是在惯用Python中的外观:

# Loop through the list until first hit.
for username, password in userPassList:  # Unpack the tuple as we fetch it.
  if username.startswith('*'):  # No mucking with indexes.
    self.conn...  # whatever
    break # We only need the first username
网友
2楼 · 发布于 2024-03-28 20:14:44

您似乎不需要索引变量。所以使用for ... in ...而不是while ... i+=1。在

for tpl in list_of_tpls:

完成后,您将有一个tuple作为itervalue,因此您可以像以前一样使用i[0]。您可能应该继续并将其存储在一个局部变量中,因为您多次引用它。它会更快,更清晰。在

^{pr2}$

字符串被视为数组/列表/元组:它们可以被索引。检查第一个字符值的方法是使用.startswith()[0]。在

^{3}$

我想剩下的都给你了。在

网友
3楼 · 发布于 2024-03-28 20:14:44

这不会产生你认为会发生的事情。在

尝试单独运行部分代码。 在编写处理该行的程序之前,请确保该行(以userPassList=开头)在语法上是正确的。在

原因如下:

 username = 'me'
 username2 = 'me2'
 username3= 'me3'
 password = password2 = password3 = ''
 userPassList=[(*username,password),(username2,password2),(username3,password3)]
 print(userPassList)
 [('m', 'e', ''), ('me2', ''), ('me3', '')]

在本例中,“*”将为您提供一个iterable并进行迭代,以便元组比预期的长。在

也许你的意思是:

^{pr2}$

那么剩下的编程工作就更有意义了。在

相关问题 更多 >