Adjacency matrix in Python

后端 未结 4 820
我寻月下人不归
我寻月下人不归 2021-02-06 03:43

I cannot find any clear explanation as to how to create an adjacency matrix in Python, with weights taken into consideration. I assume it should be relatively simple to create.<

4条回答
  •  天命终不由人
    2021-02-06 04:36

    This converts your "adjacency list" (really a dict, not a list) into a genuine matrix:

    import networkx as nx
    
    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'}]}
    new_graph = nx.Graph()
    for source, targets in graph.iteritems():
        for inner_dict in targets:
            assert len(inner_dict) == 1
            new_graph.add_edge(int(source) - 1, int(inner_dict.keys()[0]) - 1,
                               weight=inner_dict.values()[0])
    adjacency_matrix = nx.adjacency_matrix(new_graph)
    

    (The format of your graph is not particularly convenient for use in networkx.) networkx supports all kinds of operations on graphs and their adjacency matrices, so having the graph in this format should be very helpful for you. Note also that I've shifted your graph to use Python indices (i.e., starting at 0).

    In [21]: adjacency_matrix
    Out[21]: 
    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.]])
    

提交回复
热议问题