在 Python 中迭代元组列表,尝试根据特定条件删除元素criteria:
for tup in somelist: if determine(tup): # How to remove 'tup'?
要在迭代时删除项目,一种方法是创建一个仅包含所需元素的新列表:
somelist = [x for x in somelist if not determine(x)]
或者,分配给切片 somelist[:] 突变现有列表:
somelist[:] = [x for x in somelist if not determine(x)]
对于直接突变, itertools 模块提供了 filterfalse 函数:
from itertools import ifilterfalse somelist[:] = ifilterfalse(determine, somelist)
from itertools import filterfalse somelist[:] = filterfalse(determine, somelist)
以上是如何在 Python 中迭代时安全地从列表中删除项目?的详细内容。更多信息请关注PHP中文网其他相关文章!