Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

python - 如何在迭代时从列表中删除项目?(How to remove items from a list while iterating?)

I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.

(我正在遍历Python中的元组列表,并尝试在满足特定条件的情况下将其删除。)

for tup in somelist:
    if determine(tup):
         code_to_remove_tup

What should I use in place of code_to_remove_tup ?

(我应该用什么代替code_to_remove_tup ?)

I can't figure out how to remove the item in this fashion.

(我不知道如何以这种方式删除项目。)

  ask by lfaraone translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)]

Or, by assigning to the slice somelist[:] , you can mutate the existing list to contain only the items you want:

(或者,通过将切片分配给somelist[:] ,您可以将现有列表突变为仅包含所需的项目:)

somelist[:] = [x for x in somelist if not determine(x)]

This approach could be useful if there are other references to somelist that need to reflect the changes.

(如果还有其他引用要反映更改的somelist ,则此方法可能很有用。)

Instead of a comprehension, you could also use itertools .

(除了理解之外,您还可以使用itertools 。)

In Python 2:

(在Python 2中:)

from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)

Or in Python 3:

(或在Python 3中:)

from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...