Python 2d array boolean reduction

  • A+
Category:Languages

I've got a 2D array comprised of boolean values (True,False). I'd like to consolidate the array to a 1D based on a logical function of the contents.

e.g. Input:

[[True, True, False],  [False, False, False],  [True, True, True]] 

Output (logical AND):

[False,  False,  True] 

How would this be done without a loop ?

 


You can do this without NumPy too. Here is one solution using list comprehension. Explanation: It will loop over sub-lists and even if one of the items in each sub-list is False, it outputs False else True.

inp = [[True, True, False],[False, False, False],[True, True, True]] out = [False if False in i else True for i in inp] print (out)  # [False, False, True] 

Alternative (less verbose) as suggested by Jean below:

out = [False not in i for i in inp] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: