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)]
}

如何以列表列表的形式输出等效的邻接矩阵,尤其是对于加权邻接列表。我应用了 的 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

它returnsValueError: ('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]]