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

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

    Straightforward Python:

    N = 3
    data = [1, 10, 2, 9, 3, 8, 4, 7]
    
    def matchCondition(x):
        return x < 5
    
    c = 1
    l = []
    for x in data:
        if c > N or not matchCondition(x):
            l.append(x)
        else:
            c += 1
    
    print(l)
    

    This can easily be turned into a generator if desired:

    def filter_first(n, func, iterable):
        c = 1
        for x in iterable:
            if c > n or not func(x):
                yield x
            else:
                c += 1
    
    print(list(filter_first(N, matchCondition, data)))
    

提交回复
热议问题