Delete many elements of list (python)

前端 未结 5 1394
小蘑菇
小蘑菇 2021-02-07 08:03

I have a list L.

I can delete element i by doing:

del L[i]

But what if I have a set of non contiguous indexes to delete?



        
5条回答
  •  悲&欢浪女
    2021-02-07 08:31

    You can use numpy.delete as follows:

    import numpy as np
    a = ['a', 'l', 3.14, 42, 'u']
    I = [1, 3, 4]
    np.delete(a, I).tolist()
    # Returns: ['a', '3.14']
    

    If you don't mind ending up with a numpy array at the end, you can leave out the .tolist(). You should see some pretty major speed improvements, too, making this a more scalable solution. I haven't benchmarked it, but numpy operations are compiled code written in either C or Fortran.

提交回复
热议问题