从列表生成邻接矩阵,其中邻接表示元素相等

Generate adjacency matrix from a list, where adjacency means equal elements

我有一个这样的列表:

lst = [0, 1, 0, 5, 0, 1]

我想生成邻接矩阵:

out = 
array([[ 1.,  0.,  1.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  1.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  1.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  1.]])

其中 out[i,j] = 1 if lst[i]==lst[j]

这是我的带有两个 for 循环的代码:

lst = np.array(lst)
label_lst = list(set(lst))
out = np.eye(lst.size, dtype=np.float32)
for label in label_lst:
  idx = np.where(lst == label)[0]
  for pair in itertools.combinations(idx,2):
    out[pair[0],pair[1]] = 1
    out[pair[1],pair[0]] = 1

但我觉得应该有办法改善这一点。有什么建议吗?

使用broadcasted comparison-

np.equal.outer(lst, lst).astype(int) # or convert to float

样本运行-

In [787]: lst = [0, 1, 0, 5, 0, 1]

In [788]: np.equal.outer(lst, lst).astype(int)
Out[788]: 
array([[1, 0, 1, 0, 1, 0],
       [0, 1, 0, 0, 0, 1],
       [1, 0, 1, 0, 1, 0],
       [0, 0, 0, 1, 0, 0],
       [1, 0, 1, 0, 1, 0],
       [0, 1, 0, 0, 0, 1]])

或者转换为数组然后手动扩展为2D并比较-

In [793]: a = np.asarray(lst)

In [794]: (a[:,None]==a).astype(int)
Out[794]: 
array([[1, 0, 1, 0, 1, 0],
       [0, 1, 0, 0, 0, 1],
       [1, 0, 1, 0, 1, 0],
       [0, 0, 0, 1, 0, 0],
       [1, 0, 1, 0, 1, 0],
       [0, 1, 0, 0, 0, 1]])

虽然@Divakar 的建议非常好,但我将把它留在这里作为没有 numpy 的解决方案。

lst = [0, 1, 0, 5, 0, 1]
print([[1 if x==y else 0 for x in lst ] for y in lst])

同样对于大型列表,公认的解决方案要快得多。