对任意数量的列表进行按位“与”

Taking bitwise '&' of arbitrary number of lists

我有任意数量的列表,我想对其进行布尔值 &。例如,对于 2 个列表,我有

x = [0, 1, 0, 0]
y = [1, 1, 0, 1]

[np.array(x) & np.array(y) for x,y in zip(x, y)]
[0, 1, 0, 0]

3 个列表

z=[0,1,1,1]

我会

[np.array(x) & np.array(y) & np.array(y) for x,y,z in zip(x, y, z)]
[0, 1, 0, 0]

等等,

因为我有任意数量的列表来执行此操作,实现此操作的最佳方法是什么?

您可以使用 zipall:

x = [0,1,0,0]
y = [1,1,0,1]
z = [0,1,1,1]

output = [all(zipped) for zipped in zip(x, y, z)]
print(output) # [False, True, False, False]

如果您确实想获得 [0,1,0,0],请使用 int(all(zipped)) 而不是 all(zipped)(但这种显式重铸在大多数情况下是多余的)。

import numpy as np
import functools
import operator

x = np.array([0, 1, 0, 0])
y = np.array([1, 1, 0, 1])
z = np.array([0, 1, 1, 1])

print(functools.reduce(operator.and_, [x, y, z]))

既然你正在使用numpy,那么你可以使用:

np.bitwise_and.reduce(np.array([x,y,z]))

示例:

>>> x = [0, 1, 0, 0]
>>> y = [1, 1, 0, 1]
>>> z = [0, 1, 1, 1]
>>> np.bitwise_and.reduce([x, y, z])
array([0, 1, 0, 0])

但我不会为此使用 numpy just。我可能会同意 j1-lee 的回答。

只是为了好玩,这是该答案的另一个版本:

>>> from functools import partial, reduce
>>> import operator as op
>>> list(map(partial(reduce, op.and_), zip(x,y,z)))
[0, 1, 0, 0]
>>>

因为您在压缩数据上映射缩减操作

或使用np.logical_and

x = [0, 1, 0, 1]
y = [1, 1, 0, 1]
z = [1, 1, 0, 1]

np.logical_and(x, y, z).astype(int)
array([0, 1, 0, 1])

10 就像 True 和 False 所以使用 product 有效

  lists=[x,y,z]
  np.prod(lists,axis=0)

有地图和分钟:

x = [0,1,0,0]
y = [1,1,0,1]
z = [0,1,1,1]

output = list(map(min, x, y, z))
print(output)

输出(Try it online!):

[0, 1, 0, 0]

Wikipedia 顺便说一句,甚至提到对 and/or 使用 min/max。

如果你有一个 list 列表(正如“任意数字”所暗示的那样,因为你不想使用任意数量的变量),你可以使用 list(map(min, *lists)).