Why does this for loop stop before removing all items in the list?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 | L = 10*[1] for l in L: L.remove(l) print(L) |
为什么print(l)返回原始列表l的5个术语?我正在查看调试器,本地和全局的(l)长度都是5,而l.remove(1)是列表[1,1,1,1,1]上的有效操作,对吗?当len(l)为5时,什么使循环退出?
这是因为您在对列表进行迭代时正在对它进行修改。一旦删除了5个项,就消除了循环迭代的任何进一步索引。循环正在迭代列表的索引位置,从索引位置0到列表中的最后一个索引。由于您在每次迭代期间都要删除项,所以您正在更改列表中项的索引位置,但这不会更改循环将迭代的下一个索引值。
如果您有一个具有诸如
循环结束后,您将删除所有奇数值项(保留
下面是一个实践中如何工作的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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] |