any() function in Python with a callback

前端 未结 8 1135
别那么骄傲
别那么骄傲 2020-12-13 01:34

The Python standard library defines an any() function that

Return True if any element of the iterable is true. If the iterable is empty, return False.

8条回答
  •  轮回少年
    2020-12-13 02:14

    If you really want to inline a lambda in any() you can do this:

    >>> any((lambda: isinstance(e, int))() for e in [1,2,'joe'])
    True
    >>> any((lambda: isinstance(e, int))() for e in ['joe'])
    False
    

    You just have to wrap up the unnamed lambda and ensure it is invoked on each pass by appending the ()

    The advantage here is that you still get to take advantage of short circuiting the evaluation of any when you hit the first int

提交回复
热议问题