bard bard - 1 year ago 117
Python Question

Combining 3 boolean masks in Python

I have 3 lists:

a = [True, False, True]
b = [False, False, True]
c = [True, True, False]

When I type

a or b or c

I want to get back a list that's

[True, True, True]

but I'm getting back

[True, False, True]

Any ideas on why? And how can I combine these masks?

Answer Source

Your or operators are comparing the lists as entire objects, not their elements. Since a is not an empty list, it evaluates as true, and becomes the result of the or. b and c are not even evaluated.

To produce the logical OR of the three lists position-wise, you have to iterate over their contents and OR the values at each position. To convert a bunch of iterables into a list of their grouped elements, use zip(). To check if any element in an iterable is true (the OR of its entire contents), use any(). Do these two at once with a list comprehension:

mask = [any(tup) for tup in zip(a, b, c)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download