What is the idiomatic Python way to test if all elements in a collection satisfy a condition? (The .NET All()
method fills this niche nicely in C#.)
什么是惯用的Python方法来测试集合中的所有元素是否满足条件? (.NET All()方法在C#中很好地填补了这个空白。)
There's the obvious loop method:
有明显的循环方法:
all_match = True
for x in stuff:
if not test(x):
all_match = False
break
And a list comprehension could do the trick, but seems wasteful:
列表理解可以做到这一点,但似乎很浪费:
all_match = len([ False for x in stuff if not test(x) ]) > 0
There's got to be something more elegant... What am I missing?
必须有更优雅的东西......我错过了什么?
1 个解决方案
#1
25
all_match = all(test(x) for x in stuff)
This short-circuits and doesn't require stuff to be a list -- anything iterable will work -- so has several nice features.
这种短路并不需要填充列表 - 任何可迭代的东西都可以工作 - 所以有几个不错的功能。
There's also the analogous
还有类似的
any_match = any(test(x) for x in stuff)
#1
25
all_match = all(test(x) for x in stuff)
This short-circuits and doesn't require stuff to be a list -- anything iterable will work -- so has several nice features.
这种短路并不需要填充列表 - 任何可迭代的东西都可以工作 - 所以有几个不错的功能。
There's also the analogous
还有类似的
any_match = any(test(x) for x in stuff)