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

前端 未结 2 1029
长发绾君心
长发绾君心 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 as that one argument:

    any(x > 10 for x in l)
    

    Here the predicate is in the expression side of the generator expression, but you can use any expression there, including using functions.

    Demo:

    >>> l = range(10)
    >>> any(x > 10 for x in l)
    False
    >>> l = range(20)
    >>> any(x > 10 for x in l)
    True
    

    The generator expression will be iterated over until any() finds a True result, and no further:

    >>> from itertools import count
    >>> endless_counter = count()
    >>> any(x > 10 for x in endless_counter)
    True
    >>> # endless_counter last yielded 11, the first value over 10:
    ...
    >>> next(endless_counter)
    12
    

提交回复
热议问题