Remove items from a list while iterating without using extra memory in Python

后端 未结 8 880
生来不讨喜
生来不讨喜 2020-12-10 05:45

My problem is simple: I have a long list of elements that I want to iterate through and check every element against a condition. Depending on the outcome of the condition I

相关标签:
8条回答
  • 2020-12-10 06:18

    If you perform a reverse iteration, you can remove elements on the fly without affecting the next indices you'll visit:

    numbers = range(20)
    
    # remove all numbers that are multiples of 3
    l = len(numbers)
    for i, n in enumerate(reversed(numbers)):
        if n % 3 == 0:
            del numbers[l - i - 1]
    
    print numbers
    

    The enumerate(reversed(numbers)) is just a stylistic choice. You may use a range if that's more legible to you:

    l = len(numbers)
    for i in range(l-1, -1, -1):
        n = numbers[i]
        if n % 3 == 0:
            del numbers[i]
    

    If you need to travel the list in order, you can reverse it in place with .reverse() before and after the reversed iteration. This won't duplicate your list either.

    0 讨论(0)
  • 2020-12-10 06:20

    How about this?

    [x for x in list_of_g if not subtle_condition(x)]
    

    its return the new list with exception from subtle_condition

    0 讨论(0)
提交回复
热议问题