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?
We combine Boolean values using four main logical operators (or logical connectives): not, and, or, and ==. All decisions that can be made by Python—or any computer language, for that matter—can be made using these logical operators.
const arr = [[true,false,false],[false,false,false],[false,false,true]]; We are required to write a function that merges this array of arrays into a one-dimensional array by combining the corresponding elements of each subarray using the AND (&&) operator.
With * operator The * operator can repeat the same value required number of times. We use it to create a list with a Boolean value.
A boolean list ("blist") is a list that has no holes and contains only true and false . Boolean lists can be represented in an efficient compact form, see 22.5 for details. Boolean lists are lists and all operations for lists are therefore applicable to boolean lists.
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, returnFalse
.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With