2017-10-28 135 views
3

我有这样的列表:从列表,其中邻接装置相等的元素生成邻接矩阵

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 

但我觉得应该有一种方法来改善这一点。任何建议?

回答

3

使用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]]) 
+0

它看起来像一个非常整洁的解决方案(+ 1) –

2

虽然从@Divakar建议非常好,我将这里留下来作为一个没有numpy的解决方案。

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

此外,对于大型列表,接受的解决方案要快得多。