【问题标题】:Why does this for loop stop before removing all items in the list? [duplicate]为什么这个 for 循环在删除列表中的所有项目之前停止? [复制]
【发布时间】:2019-03-30 06:22:08
【问题描述】:
L = 10*[1]
for l in L:
    L.remove(l)
print(L)

为什么 print(L) 返回原始列表 L 的 5 个项?我正在查看调试器,本地和全局 (L) 的 len 都是 5,而 L.remove(1) 是列表 [1,1,1,1,1] 上的有效操作,对吗?当 len(L) 为 5 时,是什么导致循环退出?

【问题讨论】:

    标签: python list for-loop


    【解决方案1】:

    这是因为您在迭代列表L 时对其进行了变异。删除 5 个项目后,您就消除了循环迭代的任何其他索引。该循环正在遍历列表的索引位置,从索引位置 0 到列表中的最后一个索引。由于您在每次迭代期间删除项目,因此您正在更改列表中项目的索引位置,但这不会更改循环将迭代的下一个索引值。

    如果您有一个包含唯一项目值的列表,例如[1,2,3,4,5,6,7,8,9,10],这将更容易查看。在第一次迭代中,您删除项目值 1,将列表更改为 [2,3,4,5,6,7,8,9,10],然后第二次迭代转到索引位置 1,现在是项目值 3,然后删除该项目。

    当您的循环结束时,您将删除所有奇数值项(留下[2, 4, 6, 8, 10])并且循环将停止,因为列表中不再存在索引位置 5。

    这是一个实际工作的示例:

    items = [1,2,3,4,5,6,7,8,9,10]
    
    for i, item in enumerate(items):
        print(f'Iterating over index {i} where item value {item}')
        print(f'Next item: {items[i+1]}')
        items.remove(item)
        if i < len(items) - 1:
            print(f'Oops, next item changed to {items[i+1]} because I removed an item.')
        else:
            print('Oops, no more items because I removed an item.')
    
    print(f'Mutated list after loop completed: {items}')
    
    # OUTPUT
    # Iterating over index 0 where item value 1
    # Next item: 2
    # Oops, next item changed to 3 because I removed an item.
    # Iterating over index 1 where item value 3
    # Next item: 4
    # Oops, next item changed to 5 because I removed an item.
    # Iterating over index 2 where item value 5
    # Next item: 6
    # Oops, next item changed to 7 because I removed an item.
    # Iterating over index 3 where item value 7
    # Next item: 8
    # Oops, next item changed to 9 because I removed an item.
    # Iterating over index 4 where item value 9
    # Next item: 10
    # Oops, no more items because I removed an item.
    # Mutated list after loop completed: [2, 4, 6, 8, 10]
    

    【讨论】:

    • 为什么下一个循环迭代转到索引位置一? .remove(x) 函数不是定义为 x 是对象而不是索引吗?编辑:感谢您的回答!
    • 我喜欢这个答案,但它属于带有相同问题的标记重复项之一。这也符合您的利益:随着时间的推移,好的答案更有可能吸引对规范的支持(获得更多观点)。
    • @jpp 同意这个问题之前已经被问过和回答过。似乎 OP 对“为什么”比“如何”更感兴趣,虽然 dups 简要地解决了“为什么”,但他们更关注“如何”。这只是为了解释为什么我完全回答了这个问题,而不是立即将其标记为重复,但我完全同意您将其标记为重复。
    • @benvc,当然,我非常感谢您的回答。我只是觉得更多人将能够阅读和欣赏非常流行的副本(通过谷歌等),而这个问题很可能会获得更多的观点,然后消失所有意图.
    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 2015-08-19
    • 2012-05-20
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    相关资源
    最近更新 更多