如何在迭代时从列表中删除项目? [英] How to remove items from a list while iterating?

查看:43
本文介绍了如何在迭代时从列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆