组合布尔列表的最“Pythonic”方式是什么?
我有一组布尔值(就是只有真和假的值),我想用逻辑运算符“与”和“或”把它们组合起来。具体的操作是:
vals = [True, False, True, True, True, False]
# And-ing them together
result = True
for item in vals:
result = result and item
# Or-ing them together
result = False
for item in vals:
result = result or item
有没有简单的一行代码可以实现上面的操作呢?
2 个回答
15
最好的方法是使用 any()
和 all()
这两个函数。
vals = [True, False, True, True, True]
if any(vals):
print "any() reckons there's something true in the list."
if all(vals):
print "all() reckons there's no non-True values in the list."
if any(x % 4 for x in range(100)):
print "One of the numbers between 0 and 99 is divisible by 4."
128
看看 all(iterable)
:
如果这个可迭代对象(比如列表、元组等)里的所有元素都是真的(或者说这个可迭代对象是空的),那么就返回
True
。
还有 any(iterable)
:
如果这个可迭代对象里有任何一个元素是真的,就返回
True
。如果这个可迭代对象是空的,那就返回False
。