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

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

    One way using itertools.filterfalse and itertools.count:

    from itertools import count, filterfalse
    
    data = [1, 10, 2, 9, 3, 8, 4, 7]
    output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)
    

    Then list(output), gives you:

    [10, 9, 8, 4, 7]
    
    0 讨论(0)
提交回复
热议问题