为了清楚起见,添加一些print
语句:
x = range(10)
for index, number in enumerate(x):
print "x is ", x
print "element is", number
print "index is ", index
print
if number % 2 == 0:
x.remove(number)
和输出:
x is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
element is 0
index is 0
x is [1, 2, 3, 4, 5, 6, 7, 8, 9]
element is 2
index is 1
x is [1, 3, 4, 5, 6, 7, 8, 9]
element is 4
index is 2
x is [1, 3, 5, 6, 7, 8, 9]
element is 6
index is 3
x is [1, 3, 5, 7, 8, 9]
element is 8
index is 4
如您所见,即使您从列表中删除元素,它也会index
继续上升。1
这就是导致循环跳过元素的原因。
正如其他人指出的那样,遍历列表并从中删除元素并不是一个好主意。而是遍历一个副本:
for number in x[:]:
或者:
for number in list(x):
更好的是,使用列表理解创建一个新列表:
[number for number in x if number % 2 == 0]