Delete many elements of list (python)

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

    for i in I:
        del L[i]
    

    won't work, because (depending on the order) you may invalidate the iterator -- this will usually show up as some items which you intended to delete remaining in the list.

    It's always safe to delete items from the list in the reverse order of their indices. The easiest way to do this is with sorted():

    for i in sorted(I, reverse=True):
        del L[i]
    

提交回复
热议问题