如何用自定义谓词实现python的any()? [英] How to achieve python's any() with a custom predicate?

查看:146
本文介绍了如何用自定义谓词实现python的any()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> 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

d喜欢使用 any() 换而言之,但 any()只有一个参数:可迭代。有没有更好的方法?

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

推荐答案

使用 generator expression 作为那一个参数:

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

生成器表达式将通过遍历 any()找到 True 结果, p>

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

这篇关于如何用自定义谓词实现python的any()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆