2011-03-07 42 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)