在Python中检查一个谓词是否对可迭代对象中的所有元素都返回True。

63

我相信这里有一个常见的成语,但是用谷歌搜索找不到...

这是我的需求(使用Java):

// Applies the predicate to all elements of the iterable, and returns
// true if all evaluated to true, otherwise false
boolean allTrue = Iterables.all(someIterable, somePredicate);

如何用Python的"Pythonic"方式完成这个任务?

同时,如果我也能得到答案就太好了。

// Returns true if any of the elements return true for the predicate
boolean anyTrue = Iterables.any(someIterable, somePredicate);
4个回答

114

您是指这样的吗:

allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)

9
这些形式还有一个优点,即"短路":all 将在第一个 False 出现时终止,any 将在第一个 True 出现时终止。 - Don O'Donnell
6
我是唯一一个认为这个常见操作过于冗长的人吗? - cic
1
欢迎来到 Python @cic. :D 这里有更适合函数式编程的 Coconut 语言 http://coconut-lang.org/ - Ezekiel Victor

18
allTrue = all(map(predicate, iterable))
anyTrue = any(map(predicate, iterable))

1
在这里使用短路计算,您可以将“map”替换为“itertools.imap”。 - Björn Pollex
6
在Python 3中,map函数返回一个迭代器而非列表,因此不再需要使用imap函数。 - PaulMcG

3

这里有一个示例,检查列表是否全为零:

x = [0, 0, 0]
all(map(lambda v: v==0, x))
# Evaluates to True

x = [0, 1, 0]
all(map(lambda v: v==0, x))
# Evaluates to False

作为替代方案,您还可以执行以下操作:

all(v == 0 for v in x)

0
您可以在Python中使用“all”和“any”内置函数:
all(map(somePredicate, somIterable))

这里的somePredicate是一个函数,而all将检查该元素的bool()是否为True。


如果你正在使用Python 2,因为你正在链接mapall,这在最坏情况下具有O(2n)的时间复杂度。除非你的可迭代对象非常小,否则我不建议这样做。...如果你正在使用Python 3,map返回一个可迭代对象,所以这不是问题。 - mklbtz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接