迭代时如何从列表中删除项目? [英] How to remove items from a list while iterating?
问题描述
我正在迭代Python中的元组列表,并且如果它们符合某些条件,我会尝试删除它们。
I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
for tup in somelist:
if determine(tup):
code_to_remove_tup
我应该用什么代替 code_to_remove_tup
?我无法弄清楚如何以这种方式删除项目。
What should I use in place of code_to_remove_tup
? I can't figure out how to remove the item in this fashion.
推荐答案
您可以使用列表推导来创建新的列表只包含您不想删除的元素:
You can use a list comprehension to create a new list containing only the elements you don't want to remove:
somelist = [x for x in somelist if not determine(x)]
或者,通过分配给切片 somelist [:]
,您可以改变现有列表以仅包含您想要的项目:
Or, by assigning to the slice somelist[:]
, you can mutate the existing list to contain only the items you want:
somelist[:] = [x for x in somelist if not determine(x)]
如果还有其他方法,此方法可能很有用引用 somelist
需要反映更改。
This approach could be useful if there are other references to somelist
that need to reflect the changes.
除了理解,您还可以使用 itertools
。在Python 2中:
Instead of a comprehension, you could also use itertools
. In Python 2:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
或者在Python 3中:
Or in Python 3:
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
这篇关于迭代时如何从列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!