我在交互式解释器中尝试了一些列表,我注意到了这一点:
>>> list = range(1, 11)
>>> for i in list:
... list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]
有谁可以解释为什么它会留下偶数?这让我很困惑......非常感谢。
答案 0 :(得分:7)
你正在迭代modify a list是不安全的。
答案 1 :(得分:4)
我的猜测是for循环的实现如下:
list = range(1, 11)
i = 0
while i < len(list):
list.remove(list[i])
i += 1
print(list)
每次删除元素时,“next”元素都会滑入其中,但i
无论如何都会增加,跳过2个元素。
但是,是的,ObscureRobot是对的,这样做并不安全(这可能是未定义的行为)。
答案 2 :(得分:3)
如果要在迭代时修改列表,请从后到前进行操作:
lst = range(1, 11)
for i in reversed(lst):
lst.remove(i)
答案 3 :(得分:2)
我发现使用Python最容易解释:
>>> for iteration, i in enumerate(lst):
... print 'Begin iteration', iteration, 'where lst =', str(lst), 'and the value at index', iteration, 'is', lst[iteration]
... lst.remove(i)
... print 'End iteration', iteration, 'where lst =', str(lst), 'with', i, 'removed\n'
...
Begin iteration 0 where lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and the value at index 0 is 1
End iteration 0 where lst = [2, 3, 4, 5, 6, 7, 8, 9, 10] with 1 removed
Begin iteration 1 where lst = [2, 3, 4, 5, 6, 7, 8, 9, 10] and the value at index 1 is 3
End iteration 1 where lst = [2, 4, 5, 6, 7, 8, 9, 10] with 3 removed
Begin iteration 2 where lst = [2, 4, 5, 6, 7, 8, 9, 10] and the value at index 2 is 5
End iteration 2 where lst = [2, 4, 6, 7, 8, 9, 10] with 5 removed
Begin iteration 3 where lst = [2, 4, 6, 7, 8, 9, 10] and the value at index 3 is 7
End iteration 3 where lst = [2, 4, 6, 8, 9, 10] with 7 removed
Begin iteration 4 where lst = [2, 4, 6, 8, 9, 10] and the value at index 4 is 9
End iteration 4 where lst = [2, 4, 6, 8, 10] with 9 removed
请注意,(a)在迭代它时修改list
并且(b)调用list
“列表”是个坏主意。