Delete many elements of list (python)

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

    Eine Minuten bitte, Ich hap eine kleine Problemo avec diese Religione. -- Eddie Izzard (doing his impression of Martin Luther)

    Deleting by reverse-iterating over a list to preserve the iterator is a common solution to this problem. But another solution is to change this into a different problem. Instead of deleting items from the list using some criteria (in your case, the index exists in a list of indexes to be deleted), create a new list that leaves out the offending items.

    L[:] = [ item for i,item in enumerate(L) if i not in I ]
    

    For that matter, where did you come up with the indexes in I in the first place? You could combine the logic of getting the indexes to be removed and building the new list. Assuming this is a list of objects and you only want to keep those that pass an isValid test:

    L[:] = [ item for item in L if item.isValid() ]
    

    This is much more straightforward than:

    I = set()
    for i in range(len(L)):
        if not L[i].isValid():
            I.add(i)
    
    for i in sorted(I, reverse=True):
        del L[i]
    

    For the most part, I turn any question about "how to delete from a list the items that I don't want" into "how to create a new list containing just the items I want".

    EDITED: changed "L = ..." to "L[:] = ..." per Alex Martelli's answer to this question.

提交回复
热议问题