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

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

    Using list comprehensions:

    n = 3
    data = [1, 10, 2, 9, 3, 8, 4, 7]
    count = 0
    def counter(x):
        global count
        count += 1
        return x
    
    def condition(x):
        return x < 5
    
    filtered = [counter(x) for x in data if count < n and condition(x)]
    

    This will also stop checking the condition after n elements are found thanks to boolean short-circuiting.

提交回复
热议问题