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

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

    If mutation is required:

    def do_remove(ls, N, predicate):
        i, delete_count, l = 0, 0, len(ls)
        while i < l and delete_count < N:
            if predicate(ls[i]):
               ls.pop(i) # remove item at i
               delete_count, l = delete_count + 1, l - 1 
            else:
               i += 1
        return ls # for convenience
    
    assert(do_remove(l, N, matchCondition) == [10, 9, 8, 4, 7])
    

提交回复
热议问题