【发布时间】: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 时,是什么导致循环退出?
【问题讨论】:
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 时,是什么导致循环退出?
【问题讨论】:
这是因为您在迭代列表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]
【讨论】: