python - 如何使用自定义谓词实现 python 的 any()?

标签 python python-2.7 functional-programming any filterfunction

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

我想使用 any()为此,但 any() 只接受一个参数:iterable。有没有更好的办法?

最佳答案

使用 generator expression作为一个论点:

any(x > 10 for x in l)

这里的谓词在生成器表达式的表达式侧,但你可以在那里使用任何表达式,包括使用函数。

演示:

>>> l = range(10)
>>> any(x > 10 for x in l)
False
>>> l = range(20)
>>> any(x > 10 for x in l)
True

生成器表达式将迭代 直到 any() 找到 True 结果,不再进一步:

>>> 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 - 如何使用自定义谓词实现 python 的 any()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17839574/

相关文章:

r - 使用 apply 计算跨多个数据帧的分量表和总分

python - 将 MySQL 结果插入现有的 pandas 数据帧

python - 没有这样的文件或目录 : 'results.txt'

python - Conda:目标环境中缺少以下包

python - 如何将列表和其他值作为命令行参数传递?

google-app-engine - App Engine Python 模块和 channel 服务

python - Scala 的 Option 或 Either 是否有 Python 等价物?

python - 可以在 python 中创建没有日期的 datetime.date 对象吗?

python - 使用 matplotlib 绘制圆圈时出错

Clojure 中的数据库函数式编程