2011-03-07 46 views
30

相当肯定有一个常见的成语,但无法与谷歌找到它..
这是我想做的事(在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); 

回答

58

你的意思是这样的:

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

这些形式也有“短路”的优势:'all'将终止于第一个'FALSE'发生,'any'将终止第一TRUE;发生。 – 2011-03-07 08:59:01

+2

我是唯一一个认为这种常见操作无法接受的冗长的人吗? – cic 2015-06-11 20:30:58

+0

欢迎来到Python @cic。 :D有椰子更适合FP http://coconut-lang.org/ – 2017-08-07 21:32:02

6
allTrue = all(map(predicate, iterable)) 
anyTrue = any(map(predicate, iterable)) 
+2

这将遍历序列两次... – 2011-03-07 08:43:59

+1

要在这里使用短路,您可以用'itertools替换'map'。 imap'。 – 2011-03-07 09:01:15

+2

@ Space_C0wb0y - 在Python 3中,map返回一个迭代器,而不是一个列表,所以不再需要imap。 – PaulMcG 2011-03-07 16:46:24

0

您可以使用“所有”和“任何'python中的内建函数

all(map(somePredicate, somIterable)) 

这里somePredicate是一个功能 和“全部”将检查该元素的布尔()是真正的

1

下面是一个检查一个例子,如果一个列表包含所有零:

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)