矩阵列为AND运算

时间:2018-10-26 03:24:39

标签: arrays python-3.x

我的数组是

[[1. 1. 0. 0. 1.]
 [0. 1. 0. 1. 0.]
 [0. 1. 1. 0. 0.]
 [1. 1. 0. 1. 0.]
 [1. 0. 1. 0. 0.]
 [0. 1. 1. 0. 0.]
 [1. 0. 1. 0. 0.]
 [1. 1. 1. 0. 1.]
 [1. 1. 1. 0. 0.]
 [6. 7. 6. 2. 2.]]

我想用零行和第一行进行“与”运算并计算总数 像这样:

[[1. 1.] 1
 [0. 1.] 0
 [0. 1.] 0
 [1. 1.] 1
 [1. 0.] 0
 [0. 1.] 0
 [1. 0.] 0
 [1. 1.] 1
 [1. 1.]] 1

但是我要零行和第二行,零行和第三行,零行和四行,第一行和第二行,第一行和第三行....继续前进 像这样:

 row[0]row[1] , row[0]row[2] , row[0]row[3] , row[0]row[4]
 row[1]row[2] , row[1]row[3] , row[1]row[4]
 row[2]row[3] , row[2]row[4]
 row[3]row[4]

我采用零行和第二行代码:

q = []
first = [int(row[0] and row[1])for row in array[:-1]]
c = sum(first)
q.append(c)
print(c)

我该怎么办? 我使用Python3和Numpy。

2 个答案:

答案 0 :(得分:1)

听起来您想要所有列的组合,可以使用itertools.combinations()来获取组合,并使用几个zip()调用来获取想要的内容:

In []:
[[int(all(r)) for r in zip(*p)] for p in it.combinations(zip(*a[:-1]), r=2)]

Out[]:
[[1, 0, 0, 1, 0, 0, 0, 1, 1],
 [0, 0, 0, 0, 1, 0, 1, 1, 1],
 [0, 0, 0, 1, 0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0, 0, 0, 1, 0],
 [0, 0, 1, 0, 0, 1, 0, 1, 1],
 [0, 1, 0, 1, 0, 0, 0, 0, 0],
 [1, 0, 0, 0, 0, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0]]

或者如果您需要将结果转置为列:

In []:
list(zip(*[[int(all(r)) for r in zip(*p)] for p in it.combinations(zip(*a[:-1]), r=2)]))

Out[]:
[(1, 0, 0, 1, 0, 0, 1, 0, 0, 0),
 (0, 0, 0, 0, 0, 1, 0, 0, 0, 0),
 (0, 0, 0, 0, 1, 0, 0, 0, 0, 0),
 (1, 0, 1, 0, 0, 1, 0, 0, 0, 0),
 (0, 1, 0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 1, 0, 0, 0, 0, 0),
 (0, 1, 0, 0, 0, 0, 0, 0, 0, 0),
 (1, 1, 0, 1, 1, 0, 1, 0, 1, 0),
 (1, 1, 0, 0, 1, 0, 0, 0, 0, 0)]

答案 1 :(得分:1)

[[int(m[k][i] and m[k][j])
  for k in range(len(m))
 ] for i, j in combinations(range(len(m[0])), 2)]

如果您还想查看每个子结果对哪些列进行了AND操作:

{(i, j): [int(m[k][i] and m[k][j])
  for k in range(len(m))
 ] for i, j in combinations(range(len(m[0])), 2)}