0

For combining two lists of booleans based on OR, np.logical_or can be used, and similarity AND can be done with np.logical_and.

However, if I have a list of 10 lists of boolean values and want to combine them using either AND or OR, I cannot find an easy way to do this.

Could you please suggest the most efficient way?

EDIT:

booleans = [[True, True, False, True, False], [True, False, False, False, False], [True, False, False, False, False]]

OR output: [True, True, False, True, False]

AND output: [True, False, False, False, False]

Thanks, Jack

Jack Arnestad
  • 1,845
  • 13
  • 26
  • 2
    can you add an example of input -> output? – Fuxi Aug 03 '18 at 13:17
  • What do you mean by combining lists here? – AGN Gazer Aug 03 '18 at 13:17
  • Should the implementation use `numpy`? – ktb Aug 03 '18 at 13:18
  • 2
    If you're want a NumPy array as output, use `numpy.logical_and.reduce` - or more generally [`ufunc.reduce`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html). – miradulo Aug 03 '18 at 13:18
  • 2
    Possible duplicate of [Numpy \`logical\_or\` for more than two arguments](https://stackoverflow.com/questions/20528328/numpy-logical-or-for-more-than-two-arguments) – jfowkes Aug 03 '18 at 13:20
  • @miradulo @jfowkes If I do that, I get an error `TypeError: Internal Numpy error: too many arguments in call to PyUFunc_HasOverride`. I am combining around 500 of these boolean lists with or operator (`np.logical_or.reduce(*list_)`) – Jack Arnestad Aug 03 '18 at 13:23
  • @JackArnestad Don't unpack the list in your call. Also, is your intent indeed to use NumPy here? – miradulo Aug 03 '18 at 13:24
  • 1
    I commented because if OP is using NumPy this is a many-times-over duplicate. `np.any` and `np.all` are accomplishing the same thing as well. – miradulo Aug 03 '18 at 14:09

1 Answers1

8

Here is a solution without numpy

>>> booleans = [[True, True, False, True, False], [True, False, False, False, False], [True, False, False, False, False]]
>>> or_output = list(map(any, zip(*booleans)))
>>> and_output = list(map(all, zip(*booleans)))
>>> 
>>> print (or_output)
[True, True, False, True, False]
>>> print (and_output)
[True, False, False, False, False]
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23