矩阵列为AND操作

问题描述 投票:-1回答:2

我的阵列是

[[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.]]

我想取零行和第一行来做“AND”操作并计算总数如下:

[[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。

arrays python-3.x
2个回答
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)]

如果您还想查看每个子结果的ANDed的哪些列:

{(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)}

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)]
© www.soinside.com 2019 - 2024. All rights reserved.