为什么这个for-循环不贯穿所有项目:
temp = 0
for br in my_list :
temp +=1
#other code here
#my list is not used at all, only br is used inside here
my_list.remove(br)
print temp
assert len(my_list) == 0 , "list should be empty"所以断言引发了。然后我添加了临时计数器,我确实看到,尽管我的列表中有202个元素,但for循环进程中只有101个元素。为什么会这样呢?
发布于 2015-06-16 11:42:35
tobias_k是正确的,从正在迭代的列表中删除项会导致各种问题。
在本例中,通过使用repl在每个循环上打印列表,可以相对容易地显示它导致迭代跳过:
for br in my_list:
my_list.remove(br)
print my_list这就产生了:
[1, 2, 3, 4, 5]
[1, 3, 4, 5]
[1, 3, 5]并最终离开含有: 1,3,5的my_list
要做您想做的事情,mic4ael是正确的--最简单的(尽管可能不是最有效的)方法是在迭代列表之前获取它的副本,如下所示:
my_list = [0,1,2,3,4,5]
for br in my_list[:]: #The [:] takes a copy of my_list and iterates over it
my_list.remove(br)
print my_list这就产生了:
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]https://stackoverflow.com/questions/30866217
复制相似问题