迭代时从集合中删除项目 [英] delete items from a set while iterating over it
问题描述
我有一个集合 myset
,我有一个函数可以迭代它以对其项目执行一些操作,这个操作最终会从集合中删除项目.
显然,我无法在迭代原始集合的同时做到这一点.但是,我可以这样做:
mylist = list(myset)对于 mylist 中的项目:#做某事
有没有更好的方法?
首先,使用集合,正如零比雷埃夫斯告诉我们的,你可以
myset = set([3,4,5,6,2])而我的:myset.pop()打印(我的)
我添加了一个 print
方法来提供这些输出
如果你想坚持你对列表的选择,我建议你使用列表理解深度复制列表,并循环复制,同时从原始列表中删除项目.在我的示例中,我在每个循环中减少原始列表的长度.
l = list(myset)l_copy = [x for x in l]对于 l_copy 中的 k:l = l[1:]打印(升)
给予
<预><代码>>>>[3, 4, 5, 6][4, 5, 6][5, 6][6][]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.
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?
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 print
method giving these outputs
>>>
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]
[]
这篇关于迭代时从集合中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!