Python2.7 - 循环中的 list.remove(item) 给出了意想不到的行为 [英] Python2.7 - list.remove(item) within a loop gives unexpected behaviuor
本文介绍了Python2.7 - 循环中的 list.remove(item) 给出了意想不到的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除列表中的所有偶数.但是有一点让我困惑...这是代码.
I want to remove all even numbers in a list. But something confused me... This is the code.
lst = [4,4,5,5]
for i in lst:
if i % 2 == 0:
print i
lst.remove(i)
print lst
它打印 [4, 5, 5] 为什么不打印 [5, 5]?
It prints [4, 5, 5] Why not [5, 5]?
推荐答案
应该是这样的
for i in lst[:]:
if i % 2 == 0:
print i
lst.remove(i)
print lst
问题:
您在迭代列表时正在修改列表.因此,迭代在完成之前就停止了
You are modifying the list while you iterate over it. Due to which the iteration is stopped before it could complete
解决方案:
您可以遍历列表的副本
你可以使用 list comprehension
:
lst=[i for i in lst if i%2 != 0]
这篇关于Python2.7 - 循环中的 list.remove(item) 给出了意想不到的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文