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

后端 未结 7 1115
余生分开走
余生分开走 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:38

    The accepted answer was a little too magical for my liking. Here's one where the flow is hopefully a bit clearer to follow:

    def matchCondition(x):
        return x < 5
    
    
    def my_gen(L, drop_condition, max_drops=3):
        count = 0
        iterator = iter(L)
        for element in iterator:
            if drop_condition(element):
                count += 1
                if count >= max_drops:
                    break
            else:
                yield element
        yield from iterator
    
    
    example = [1, 10, 2, 9, 3, 8, 4, 7]
    
    print(list(my_gen(example, drop_condition=matchCondition)))
    

    It's similar to logic in davidism answer, but instead of checking the drop count is exceeded on every step, we just short-circuit the rest of the loop.

    Note: If you don't have yield from available, just replace it with another for loop over the remaining items in iterator.

提交回复
热议问题