[英]What is the most 'pythonic' way to logically combine a list of booleans?
I have a list of booleans I'd like to logically combine using and/or. 我有一个布尔列表我想用逻辑组合使用和/或。 The expanded operations would be:
扩展的业务将是:
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
Are there nifty one-liners for each of the above? 上面的每一个都有漂亮的单行吗?
See all(iterable)
: 查看
all(iterable)
:
Return
True
if all elements of the iterable are true (or if the iterable is empty).如果iterable的所有元素都为true(或者iterable为空),则返回
True
。
And any(iterable)
: any(iterable)
:
Return
True
if any element of the iterable is true.如果iterable的任何元素为
True
则返回True
。 If the iterable is empty, returnFalse
.如果iterable为空,则返回
False
。
The best way to do it is with the any()
and all()
functions. 最好的方法是使用
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."
Demonstrating NullUserException's answer. 演示NullUserException的答案。
In [120]: a
Out[120]:
array([[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
In [121]: a.all()
Out[121]: True
In [122]: b
Out[122]:
array([[False, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
In [123]: b.all()
Out[123]: False
In [124]: b.any()
Out[124]: True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.