Remove all occurrences of a value from a list?

后端 未结 23 1985
佛祖请我去吃肉
佛祖请我去吃肉 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:53

    Let

    >>> x = [1, 2, 3, 4, 2, 2, 3]
    

    The simplest and efficient solution as already posted before is

    >>> x[:] = [v for v in x if v != 2]
    >>> x
    [1, 3, 4, 3]
    

    Another possibility which should use less memory but be slower is

    >>> for i in range(len(x) - 1, -1, -1):
            if x[i] == 2:
                x.pop(i)  # takes time ~ len(x) - i
    >>> x
    [1, 3, 4, 3]
    

    Timing results for lists of length 1000 and 100000 with 10% matching entries: 0.16 vs 0.25 ms, and 23 vs 123 ms.

提交回复
热议问题