我正在对 Python 中的元组列表进行迭代,并尝试在它们满足某些条件时删除它们。
for tup in somelist:
if determine(tup):
code_to_remove_tup
我应该使用什么来代替code_to_remove_tup? 我不知道如何以这种方式移除这个项目。
我正在对 Python 中的元组列表进行迭代,并尝试在它们满足某些条件时删除它们。
for tup in somelist:
if determine(tup):
code_to_remove_tup
我应该使用什么来代替code_to_remove_tup? 我不知道如何以这种方式移除这个项目。
你可以使用列表内涵来创建一个新的列表,只包含你不想删除的元素:
somelist = [x for x in somelist if not determine(x)]
或者,通过分配给 slice somelist [ : ,您可以修改现有的列表,只包含您想要的条目:
somelist[:] = [x for x in somelist if not determine(x)]
如果还有需要反映更改的其他对体裁列表的引用,那么这种方法可能很有用。
除了 comprehension,您还可以在 Python 2使用 itertools:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
或者在 Python 3中也行:
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)