如何在迭代时从列表中删除项目?

问题描述:

我正在 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)