Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - delete items from a set while iterating over it

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?

question from:https://stackoverflow.com/questions/16551334/delete-items-from-a-set-while-iterating-over-it

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...