[Python] aus Liste entfernen, während man drüber iteriert?



  • Hallo,

    kann ich elemente aus einer Liste entfernen während ich über die Liste iteriere?

    for element in l:
        if property(element):
            l.remove(element)
    

    sicher, ich kann auch

    l = filter(lambda x : not property(x), l)
    

    machen... aber geht das andere?



  • Hallo,

    ja kannst du.

    Grüße
    Martin



  • anscheinend doch nicht:

    >>> a = range(10)
    >>> for i in a:
    ...     a.remove(i)
    ... 
    >>> a
    [1, 3, 5, 7, 9]
    


  • Hallo,

    probier mal das:

    l = range(10)
    for i in l[:]:
        l.remove(i)
    

    Und die Erklärung findest du dazu in der Doku:http://docs.python.org/reference/compound_stmts.html#for.

    Hier die Stelle:

    Note

    There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

    for x in a[:]:
    if x < 0: a.remove(x)

    Hoffe dir hilft das weiter.

    Grüße
    Martin



  • danke 👍


Anmelden zum Antworten