简体   繁体   English

如何对布尔对象列表进行逻辑和操作?

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

I have a list of bool objects list like this:我有一个bool对象列表,如下所示:

[[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?做这个的最好方式是什么?

As long as you use boolean, you could zip and then use all :只要你使用 boolean,你可以zip然后使用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 Output

[False, False, True, False]

You can use functools.reduce and the bitwise "and" operator.and_ , as well as the typical zip(*...) transposition pattern:您可以使用functools.reduce和按位“与” operator.and_以及典型的zip(*...)换位模式:

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]

If you want to specifically use the bitwise & operator, then you can use functools.reduce with zip :如果您想专门使用按位&运算符,则可以将functools.reducezip一起使用:

>>> 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 :我们还可以创建自己的迷你 function 来替换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.或者只使用operator模块,如@schwobaseggl 的答案所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM