any() function in Python with a callback

2019-01-21 12:28发布

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.

It checks only if the elements evaluate to True. What I want it to be able so specify a callback to tell if an element fits the bill like:

any([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0)

8条回答
看我几分像从前
2楼-- · 2019-01-21 13:05

Slight improvement to Antoine P's answer

>>> any(type(e) is int for e in [1,2,'joe'])
True

For all()

>>> all(type(e) is int for e in [1,2,'joe'])
False
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-21 13:06

filter can work, plus it returns you the matching elements

>>> filter(lambda e: isinstance(e, int) and e > 0, [1,2,'joe'])
[1, 2]
查看更多
登录 后发表回答