Delete many elements of list (python)

前端 未结 5 1388
小蘑菇
小蘑菇 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

    If your original list data can safely be turned into a set (i.e. all unique values and doesn't need to maintain order), you could also use set operations:

    Lset = set(L)
    newset = Lset.difference(I)
    

    You could also maybe do something with a Bag/Multiset, though it probably isn't worth the effort. Paul McGuire's second listcomp solution is certainly best for most cases.

提交回复
热议问题