Remove all occurrences of a value from a list?

后端 未结 23 1967
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:45

In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list?

This is w

23条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 23:59

    All of the answers above (apart from Martin Andersson's) create a new list without the desired items, rather than removing the items from the original list.

    >>> import random, timeit
    >>> a = list(range(5)) * 1000
    >>> random.shuffle(a)
    
    >>> b = a
    >>> print(b is a)
    True
    
    >>> b = [x for x in b if x != 0]
    >>> print(b is a)
    False
    >>> b.count(0)
    0
    >>> a.count(0)
    1000
    
    >>> b = a
    >>> b = filter(lambda a: a != 2, x)
    >>> print(b is a)
    False
    

    This can be important if you have other references to the list hanging around.

    To modify the list in place, use a method like this

    >>> def removeall_inplace(x, l):
    ...     for _ in xrange(l.count(x)):
    ...         l.remove(x)
    ...
    >>> removeall_inplace(0, b)
    >>> b is a
    True
    >>> a.count(0)
    0
    

    As far as speed is concerned, results on my laptop are (all on a 5000 entry list with 1000 entries removed)

    • List comprehension - ~400us
    • Filter - ~900us
    • .remove() loop - 50ms

    So the .remove loop is about 100x slower........ Hmmm, maybe a different approach is needed. The fastest I've found is using the list comprehension, but then replace the contents of the original list.

    >>> def removeall_replace(x, l):
    ....    t = [y for y in l if y != x]
    ....    del l[:]
    ....    l.extend(t)
    
    • removeall_replace() - 450us

提交回复
热议问题