How to achieve python's any() with a custom predicate?

前端 未结 2 1030
长发绾君心
长发绾君心 2021-02-07 01:12
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> if filter(lambda x: x > 10, l):
...     print \"foo\"
... else:                    


        
2条回答
  •  失恋的感觉
    2021-02-07 02:04

    Use a generator expression inside of any():

    pred = lambda x: x > 10
    if any(pred(i) for i in l):
        print "foo"
    else:
        print "bar"
    

    This assumes you already have some predicate function you want to use, of course if it is something simple like this you can just use the Boolean expression directly: any(i > 10 for i in l).

提交回复
热议问题