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?
上面的每一个都有漂亮的单行吗?
3 个解决方案
#1
81
See 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)
:
任何(可迭代的):
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
.如果iterable的任何元素为true,则返回True。如果iterable为空,则返回False。
#2
5
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."
#3
1
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
#1
81
See 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)
:
任何(可迭代的):
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
.如果iterable的任何元素为true,则返回True。如果iterable为空,则返回False。
#2
5
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."
#3
1
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