Remove all occurrences of a value from a list?

后端 未结 23 1962
佛祖请我去吃肉
佛祖请我去吃肉 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-22 00:10

    Numpy approach and timings against a list/array with 1.000.000 elements:

    Timings:

    In [10]: a.shape
    Out[10]: (1000000,)
    
    In [13]: len(lst)
    Out[13]: 1000000
    
    In [18]: %timeit a[a != 2]
    100 loops, best of 3: 2.94 ms per loop
    
    In [19]: %timeit [x for x in lst if x != 2]
    10 loops, best of 3: 79.7 ms per loop
    

    Conclusion: numpy is 27 times faster (on my notebook) compared to list comprehension approach

    PS if you want to convert your regular Python list lst to numpy array:

    arr = np.array(lst)
    

    Setup:

    import numpy as np
    a = np.random.randint(0, 1000, 10**6)
    
    In [10]: a.shape
    Out[10]: (1000000,)
    
    In [12]: lst = a.tolist()
    
    In [13]: len(lst)
    Out[13]: 1000000
    

    Check:

    In [14]: a[a != 2].shape
    Out[14]: (998949,)
    
    In [15]: len([x for x in lst if x != 2])
    Out[15]: 998949
    

提交回复
热议问题