any() function in Python with a callback

前端 未结 8 1142
别那么骄傲
别那么骄傲 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 01:59

    While the others gave good Pythonic answers (I'd just use the accepted answer in most cases), I just wanted to point out how easy it is to make your own utility function to do this yourself if you really prefer it:

    def any_lambda(iterable, function):
      return any(function(i) for i in iterable)
    
    In [1]: any_lambda([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0
    Out[1]: True
    In [2]: any_lambda([-1, '2', 'joe'], lambda e: isinstance(e, int) and e > 0)
    Out[2]: False
    

    I think I'd at least define it with the function parameter first though, since that'd more closely match existing built-in functions like map() and filter():

    def any_lambda(function, iterable):
      return any(function(i) for i in iterable)
    

提交回复
热议问题