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 return a list that

 [True, True, True] 

but i'm coming back

 [True, False, True] 

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

+7
python boolean-logic
source share
7 answers

The or operators compare lists as whole objects, not their elements. Since a not an empty list, it evaluates to true and becomes the result of or . b and c not even evaluated.

To create a logical OR from three lists by position, you need to iterate over their contents and OR values ​​at each position. To convert a bunch of iterations to a list of their grouped items, use zip() . To check if any element in iterable is true (OR of its entire contents), use any() . Do these two immediately with a list:

 mask = [any(tup) for tup in zip(a, b, c)] 
+7
source share

How about this:

 from numpy import asarray as ar a = [True, False, True] b = [False, False, True] c = [True, True, False] 

Try:

 >>> ar(a) | ar(b) | ar(c) #note also the use `|` instead of `or` array([ True, True, True], dtype=bool) 

Therefore, there is no need for zip , etc.

+9
source share

or returns the first operand if it evaluates to true and a non-empty list evaluates to true ; therefore a or b or c will always return a if it is a non-empty list.

Maybe you want

 [any(t) for t in zip(a, b, c)] 

(this also works for elementary and if you replace any with all )

+6
source share

a is considered true because it contains values; b , c not evaluated.

 >>> bool([]) False >>> bool([True]) True >>> bool([False]) True >>> [False] or [True] [False] 

According to logical operations :

The expression x or y first evaluates x ; if x true, its value is returned; otherwise, y is evaluated and the return value is returned.

+2
source share

Here's how to do it quickly (large arrays) using numpy:

 import numpy as np a = [True, False, True,...] b = [False, False, True,...] c = [True, True, False,...] res = (np.column_stack((a,b,c)).any(axis=1) print res 

Note that a becomes the first column, b second, etc. when using np.column_stack() . Then do np.any() (logical OR) on an array along axis=1 , which will compare the first elements a , b and c , etc. Etc.; the result is a logical vector whose length matches the vectors you want to compare.

+1
source share

Try the following:

 a = [True, False, True] b = [False, False, True] c = [True, True, False] res = [a[i] or b[i] or c[i] for i in range(len(a))] print res 
0
source share

What about

 result = numpy.logical_or(a, b, c) print(result) 
0
source share

All Articles