any() function in Python with a callback

前端 未结 8 1143
别那么骄傲
别那么骄傲 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:00

    You should use a "generator expression" - that is, a language construct that can consume iterators and apply filter and expressions on then on a single line:

    For example (i ** 2 for i in xrange(10)) is a generator for the square of the first 10 natural numbers (0 to 9)

    They also allow an "if" clause to filter the itens on the "for" clause, so for your example you can use:

    any (e for e in [1, 2, 'joe'] if isinstance(e, int) and e > 0)
    

提交回复
热议问题