问题
I have an adjacency matrix like:
[[ 0., 15., 0., 7., 10., 0.],
[ 15., 0., 9., 11., 0., 9.],
[ 0., 9., 0., 0., 12., 7.],
[ 7., 11., 0., 0., 8., 14.],
[ 10., 0., 12., 8., 0., 8.],
[ 0., 9., 7., 14., 8., 0.]]
How can I convert it to an adjacency list like this one down here?
graph = {'1': [{'2':'15'}, {'4':'7'}, {'5':'10'}],
'2': [{'3':'9'}, {'4':'11'}, {'6':'9'}],
'3': [{'5':'12'}, {'6':'7'}],
'4': [{'5':'8'}, {'6':'14'}],
'5': [{'6':'8'}]}
?
回答1:
Keep a list of already added edges in a set edges
. Those edges are stored in a frozenset
, so already added pairs are not replicated.
Then build your graph by enumerating the outer list with a starting index of one, then the inner list also with a starting index of one. Zero valued entries are eliminated with the if
condition on values:
from collections import defaultdict
from pprint import pprint
l =[[ 0., 15., 0., 7., 10., 0.],
[ 15., 0., 9., 11., 0., 9.],
[ 0., 9., 0., 0., 12., 7.],
[ 7., 11., 0., 0., 8., 14.],
[ 10., 0., 12., 8., 0., 8.],
[ 0., 9., 7., 14., 8., 0.]]
graph = defaultdict(list)
edges = set()
for i, v in enumerate(l, 1):
for j, u in enumerate(v, 1):
if u != 0 and frozenset([i, j]) not in edges:
edges.add(frozenset([i, j]))
graph[i].append({j: u})
pprint(graph)
# {1: [{2: 15.0}, {4: 7.0}, {5: 10.0}],
# 2: [{3: 9.0}, {4: 11.0}, {6: 9.0}],
# 3: [{5: 12.0}, {6: 7.0}],
# 4: [{5: 8.0}, {6: 14.0}],
# 5: [{6: 8.0}]}
Using a defaultdict
which takes a list
as default value will help build the list-valued dictionary on the fly.
回答2:
Function to convert a matrix into adjacency list:
def convert_matrix_to_Adj_list(self,matrix):
for i in range(0,self.V):
for j in range(0,self.V):
if matrix[i][j]:
# print(i,j)
self.graph[i].append(j)# add an edge to the graph
self.graph[j].append(i)# add an edge to the graph
来源:https://stackoverflow.com/questions/38165292/how-to-convert-an-adjacency-matrix-to-an-adjacency-list-with-python