[英]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?做这个的最好方式是什么?
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.reduce
与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
:我们还可以创建自己的迷你 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.