2011-12-27 89 views
15

什麼是Python的方式來測試集合中的所有元素是否滿足條件? (該.NET All() method在C#中很好地滿足這一市場。)相當於Python的LINQ所有函數?

有明顯的循環方法:

all_match = True 
for x in stuff: 
    if not test(x): 
     all_match = False 
     break 

和列表理解可以做的伎倆,但似乎浪費:

all_match = len([ False for x in stuff if not test(x) ]) > 0 

我們有了成爲更優雅的東西......我錯過了什麼?

+0

參見http://stackoverflow.com/questions/8641008/compare-multiple-variables-to-the-same-value-in-if-in-python – 2011-12-27 06:48:21

回答

25
all_match = all(test(x) for x in stuff) 

這短路,並且不需要的東西是一個列表 - 任何可迭代將工作 - 所以有幾個不錯的功能。

還有類似

any_match = any(test(x) for x in stuff) 
+2

哈!非常明顯!好悲傷,現在我感到很傻... – Cameron 2011-12-27 04:21:11

+0

絕對是我會走的路。然而,Python中的「all」與「Enumerable.All」不同,因爲它不直接帶謂詞。 (所以它更類似於Enumerable.Where(predicate).All()'。) – 2011-12-27 04:45:51