Python 迭代时从集合中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16551334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:58:34  来源:igfitidea点击:

delete items from a set while iterating over it

pythonpython-2.7set

提问by skyork

I have a set myset, and I have a function which iterates over it to perform some operation on its items and this operation ultimately deletes the item from the set.

我有一个 set myset,我有一个函数,它迭代它以对其项目执行一些操作,这个操作最终从集合中删除该项目。

Obviously, I cannot do it while still iterating over the original set. I can, however, do this:

显然,我不能在仍然迭代原始集合的同时做到这一点。但是,我可以这样做:

mylist = list(myset)
for item in mylist:
    # do sth

Is there any better way?

有没有更好的办法?

采纳答案by kiriloff

First, using a set, as Zero Piraeus told us, you can

首先,使用集合,正如零比雷埃夫斯告诉我们的,你可以

myset = set([3,4,5,6,2])
while myset:
    myset.pop()
    print(myset)

I added a printmethod giving these outputs

我添加了一个print提供这些输出的方法

>>> 
set([3, 4, 5, 6])
set([4, 5, 6])
set([5, 6])
set([6])
set([])

If you want to stick to your choice for a list, I suggest you deep copy the list using a list comprehension, and loop over the copy, while removing items from original list. In my example, I make length of original list decrease at each loop.

如果你想坚持你对列表的选择,我建议你使用列表理解深度复制列表,并循环复制,同时从原始列表中删除项目。在我的示例中,我在每个循环中减少原始列表的长度。

l = list(myset)
l_copy = [x for x in l]
for k in l_copy:
    l = l[1:]
    print(l)

gives

>>> 
[3, 4, 5, 6]
[4, 5, 6]
[5, 6]
[6]
[]

回答by Zero Piraeus

This ought to work:

这应该有效:

while myset:
    item = myset.pop()
    # do something

Or, if you need to remove items conditionally:

或者,如果您需要有条件地删除项目:

def test(item):
    return item != "foo"  # or whatever

myset = set(filter(test, myset))

回答by That_User

Let's return all even numbers while modifying current set.

让我们在修改当前集合时返回所有偶数。

myset = set(range(1,5))
myset = filter(lambda x:x%2==0, myset)
print myset

Will return

将返回

>>> [2, 4]

If there is opportunity use always uselambdait will make your life easier.

如果有机会使用总是使用lambda它会让你的生活更轻松。

回答by Sanjeev Kumar

Another way could be :

另一种方法可能是:

s=set()
s.add(1)
s.add(2)
s.add(3)
s.add(4)
while len(s)>0:
    v=next(iter(s))
    s.remove(v)

回答by Viktor Tóth

Use the copylibrary to make a copy of the set, iterate over the copy and remove from the original one. In case you want to stick to the forloop and you want to iterate over one element only once - comes in handy if you don't necessarily want to remove all the elements.

使用copy库制作集合的副本,迭代副本并从原始副本中删除。如果您想坚持for循环并且只想迭代一个元素一次 - 如果您不一定要删除所有元素,这会派上用场。

import copy
for item in copy.copy(myset):
    myset.remove(item)