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

邮差的信 提交于 2019-12-09 08:32:05

问题


>>> 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:                     # the list will be empty, so bar will be printed
...     print "bar"
... 
bar

I'd like to use any() for this instead, but any() only takes one argument: the iterable. Is there a better way?


回答1:


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



回答2:


Use a generator expression inside of any():

pred = lambda x: x > 10
if any(pred(i) for i in l):
    print "foo"
else:
    print "bar"

This assumes you already have some predicate function you want to use, of course if it is something simple like this you can just use the Boolean expression directly: any(i > 10 for i in l).



来源:https://stackoverflow.com/questions/17839574/how-to-achieve-pythons-any-with-a-custom-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!