如何使用python将邻接矩阵转换为邻接列表? [英] How to convert an adjacency matrix to an adjacency list with python?
问题描述
我有一个类似的邻接矩阵:
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'}]}
?
推荐答案
保留一组edges
中已添加的边的列表.这些边存储在frozenset
中,因此不会复制已添加的对.
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.
然后通过枚举以起始索引为1的外部列表,然后以起始索引为1的内部列表来构建图形.在值上使用if
条件可以消除零值条目:
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}]}
使用将list
作为默认值的defaultdict
可以帮助动态构建列表值的字典.
Using a defaultdict
which takes a list
as default value will help build the list-valued dictionary on the fly.
这篇关于如何使用python将邻接矩阵转换为邻接列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!