什么是惯用的Python方法来测试集合中的所有元素是否满足条件?(.NET All()方法在C#中很好地填补了这个空白.)
有明显的循环方法:
all_match = True
for x in stuff:
if not test(x):
all_match = False
break
Run Code Online (Sandbox Code Playgroud)
列表理解可以做到这一点,但似乎很浪费:
all_match = len([ False for x in stuff if not test(x) ]) > 0
Run Code Online (Sandbox Code Playgroud)
必须有更优雅的东西......我错过了什么?
DSM*_*DSM 25
all_match = all(test(x) for x in stuff)
Run Code Online (Sandbox Code Playgroud)
这种短路并不需要将东西作为列表 - 任何可迭代的东西都可以工作 - 所以有几个不错的功能.
也有类似的
any_match = any(test(x) for x in stuff)
Run Code Online (Sandbox Code Playgroud)