fish
fish

Reputation: 2513

How to do logical and operation on list of bool objects list?

I have a list of bool objects list like this:

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

I want to bit and those lists and get the result:

[False, False, True, False]

What is the best way to do this?

Upvotes: 1

Views: 134

Answers (3)

RoadRunner
RoadRunner

Reputation: 26315

If you want to specifically use the bitwise & operator, then you can use functools.reduce with zip:

>>> from functools import reduce
>>> l = [[True, True, True, False], [False, True, True, False], [False, False, True, True]]
>>> [reduce(lambda x, y: x & y, lst) for lst in zip(*l)]
[False, False, True, False]

We can also create our own mini function to replace lambda:

>>> def bitwise_and(x, y):
...     return x & y
...
>>> [reduce(bitwise_and, lst) for lst in zip(*l)]
[False, False, True, False]

Or just use the operator module, as shown in @schwobaseggl's answer.

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61910

As long as you use boolean, you could zip and then use all:

data = [[True, True, True, False], [False, True, True, False], [False, False, True, True]]
result = [all(e) for e in zip(*data)]
print(result)

Output

[False, False, True, False]

Upvotes: 3

user2390182
user2390182

Reputation: 73460

You can use functools.reduce and the bitwise "and" operator.and_, as well as the typical zip(*...) transposition pattern:

from functools import reduce
from operator import and_

lst = [[True, True, True, False], [False, True, True, False], [False, False, True, True]]

[reduce(and_, x) for x in zip(*lst)]
# [False, False, True, False]

Upvotes: 2

Related Questions