簡體   English   中英

Python中鄰接矩陣的鄰接列表表示

[英]Adjacency List Representation to Adjacency Matrix in Python

給定下面的兩個鄰接表表示

g = {
'I': ['J', 'K', 'M'],
'J': ['I', 'K', 'L'],
'K': ['I', 'J', 'M'],
'L': ['J'],
'M': ['I', 'K']
}

#Weighted 
g = {
'I': [('J', 1), ('K', 2), ('M', 3)],
'J': [('I', 1), ('K', 7), ('L', 5)],
'K': [('I', 2), ('J', 7), ('M', 6)],
'L': [('J', 5)],
'M': [(I, 3), (K, 6)]
}

我怎樣才能 output 以列表的形式特別是加權鄰接列表的形式的等效鄰接矩陣。 我已經應用了如何從 python 中的字典生成圖形的鄰接矩陣中的 karakfa 算法? . 但是,我似乎無法將它實施到加權圖上。

keys = sorted(g.keys())
M = [ [0]*len(keys) for i in range(len(keys)) ]
for a,b in [(keys.index(a), keys.index(b)) for a, row in g.items() for b in row]:
   M[a][b] = 1

它返回ValueError: ('J', 1) is not in list

原因是您的字典鍵是您的頂點名稱,但您傳遞的是 (vertex_name, weight) 的元組。 此外,變量名稱令人困惑,可能會導致錯誤( b被使用兩次)。

keys = sorted(g.keys())
M = [ [0]*len(keys) for i in range(len(keys)) ]
for vertex_1, row in g.items():
    for vertex_2, weight in row:
        M[keys.index(vertex_1)][keys.index(vertex_2)] = weight

這給出了:

[[0, 1, 2, 0, 3],
 [1, 0, 7, 5, 0],
 [2, 7, 0, 0, 6],
 [0, 5, 0, 0, 0],
 [3, 0, 6, 0, 0]]

暫無
暫無

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

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