delete items from a set while iterating over it

后端 未结 5 1859
忘了有多久
忘了有多久 2020-12-16 09:27

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

5条回答
  •  执念已碎
    2020-12-16 09:55

    Use the copy library 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 for loop and you want to iterate over one element only once - comes in handy if you don't necessarily want to remove all the elements.

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

提交回复
热议问题