2017-10-28 167 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]) 

此外,對於大型列表,接受的解決方案要快得多。