簡體   English   中英

從列表生成鄰接矩陣,其中鄰接意味着相等的元素

[英]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])

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM