如何使用python将邻接矩阵转换为邻接列表?

时间:2016-07-02 23:21:58

标签: python python-3.x matrix adjacency-list adjacency-matrix

我有一个邻接矩阵,如:

[[  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 = {'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'}]}

2 个答案:

答案 0 :(得分:2)

在集edges中保留已添加边的列表。这些边缘存储在frozenset中,因此不会复制已添加的对。

然后通过枚举外部列表来构建您的图表,其中起始索引为1,然后内部列表的起始索引为1。零值条目通过值if条件消除:

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

使用以defaultdict作为默认值的list将有助于动态构建列表值字典。

答案 1 :(得分:0)

将矩阵转换为邻接表的功能:

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