简体   繁体   中英

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) :

Return True if all elements of the iterable are true (or if the iterable is empty).

And any(iterable) :

Return True if any element of the iterable is true. If the iterable is empty, return False .

The best way to do it is with the any() and all() functions.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM