Performing a logical or operation of multiple lists in Python
Question:
I have a list containing some number of sublists.
list1=[ [True,False,True,False], [False,False,True,False],[True,False,True,True], .....]
I want to perform a logical or of these sublists in Python but the number of sublists is unknown. For two lists I can do numpy.logical_or
but how can I do it for multiple sublists?
Answers:
@Ian’s answer is better than my original answer. zip
all of the lists to combine their elements columnwise, performing a transposition, and run each column into any
:
>>> matrix = [
... [True, False, True, False],
... [False, False, True, False],
... [True, False, True, True],
... ]
>>> [any(column) for column in zip(*matrix)]
[True, False, True, True]
I removed my original answer which is suboptimal.
Following up @ggorlen’s answer
list1 = [
[True,False,True,False],
[False,False,True,False],
[True,False,True,True]
]
[any(l) for l in zip(*list1)]
Output
[True, False, True, True]
I have a list containing some number of sublists.
list1=[ [True,False,True,False], [False,False,True,False],[True,False,True,True], .....]
I want to perform a logical or of these sublists in Python but the number of sublists is unknown. For two lists I can do numpy.logical_or
but how can I do it for multiple sublists?
@Ian’s answer is better than my original answer. zip
all of the lists to combine their elements columnwise, performing a transposition, and run each column into any
:
>>> matrix = [
... [True, False, True, False],
... [False, False, True, False],
... [True, False, True, True],
... ]
>>> [any(column) for column in zip(*matrix)]
[True, False, True, True]
I removed my original answer which is suboptimal.
Following up @ggorlen’s answer
list1 = [
[True,False,True,False],
[False,False,True,False],
[True,False,True,True]
]
[any(l) for l in zip(*list1)]
Output
[True, False, True, True]