delete items from a set while iterating over it

后端 未结 5 1858
忘了有多久
忘了有多久 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 10:13

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

提交回复
热议问题