【问题标题】:iterating over list in list; python迭代列表中的列表; Python
【发布时间】:2020-12-16 19:35:15
【问题描述】:

我有一个简单的问题。我是 python 和编程新手,所以我想我错过了一些东西。

变量“account_info”是之前分配的,是一个列表列表,每个列表有 4 个元素。变量 current 是用户输入值,它(应该)作为列表 account_info 中列表的第一个元素出现。 我想遍历列表中的列表并比较第一个元素是否等于“当前”。 这是代码:

    for i in account_info:
        if current == account_info[i][0]:
            email = account_info[i][1]
            additional = account_info[i][2]
            pw = account_info[i][3]
    print(email)

运行该代码时,我在 pycharm 中遇到错误。似乎我无法遍历这样的列表,请有人解释并显示不同的解决方案吗?

谢谢

【问题讨论】:

  • i 中的for i in account_infoaccount_info 的元素,而不是索引。

标签: python-3.x list loops for-loop


【解决方案1】:

正如@ForceBru 评论的那样,您的问题是由于for 循环在Python 中的工作方式。您从循环中获得的值不是您正在循环的可迭代对象的索引,而是来自可迭代对象的值。这使得你以后用它建立索引几乎肯定是错误的(尽管在某些情况下它可能是有意义的,如果你有一个包含自身索引的列表)。

在你的情况下,你可能想做更多这样的事情:

for account in accounts_info:
    if current == account[0]:    # note, only the inner indexing is needed
        email = account[1]
        additional = account[2]
        pw = account[3]

由于您期望内部列表包含四个值,您甚至可以解压缩从直接迭代到内部变量中获得的 account 值。虽然这会无条件发生,但它可能不会做你想做的事。看起来是这样的,在循环之后执行 print 调用,而不是移动到条件内部(因此您只打印与 current 中的值对应的一个电子邮件地址):

for account_id, email, additional, pw in account_info:  # unpack unconditionally
    if account_id == current:                           # use the convenient name here
        print(email)                                    # print only in the conditional

在您确实需要迭代索引的极少数情况下,您可以使用range 类型,它的行为类似于整数序列(默认从零开始)。所以你可以用这个版本替换你的循环,并且主体会按照你的预期工作(尽管这比以前的版本不那么惯用的 Python)。

for i in range(len(accounts_info)):

如果您需要同时索引和当前值,您可以使用enumerate 函数,该函数在您对其进行迭代时生成索引和值的2 元组。当您有时需要重新分配列表中的值时,这通常很方便:

for i, account in enumerate(accounts_info):
    if account[0] == current:
        accounts_info[i] = new_value            # replace the whole account entry

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2014-04-26
    • 2012-05-12
    相关资源
    最近更新 更多