delete items from a set while iterating over it

后端 未结 5 1855
忘了有多久
忘了有多久 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:51

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

提交回复
热议问题