Remove the first N items that match a condition in a Python list

后端 未结 7 1096
余生分开走
余生分开走 2021-01-30 20:11

If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?

One solution is to itera

7条回答
  •  一整个雨季
    2021-01-30 20:22

    Write a generator that takes the iterable, a condition, and an amount to drop. Iterate over the data and yield items that don't meet the condition. If the condition is met, increment a counter and don't yield the value. Always yield items once the counter reaches the amount you want to drop.

    def iter_drop_n(data, condition, drop):
        dropped = 0
    
        for item in data:
            if dropped >= drop:
                yield item
                continue
    
            if condition(item):
                dropped += 1
                continue
    
            yield item
    
    data = [1, 10, 2, 9, 3, 8, 4, 7]
    out = list(iter_drop_n(data, lambda x: x < 5, 3))
    

    This does not require an extra copy of the list, only iterates over the list once, and only calls the condition once for each item. Unless you actually want to see the whole list, leave off the list call on the result and iterate over the returned generator directly.

提交回复
热议问题