繁体   English   中英

Python Networkx的加权邻接表

[英]Weighted Adjacency List with Python Networkx

我使用以下结构在Python中定义了一个图:

graph = {
    "A": {"B": 10, "C": 3},
    "B": {"C": 1, "D": 2},
    "C": {"B": 4, "D": 8, "E": 2},
    "D": {"E": 7},
    "E": {"D": 9}
}

请问有什么方法可以将它读入networkx吗?

我已经尝试了G = nx.read_adjlist(graph)并查看了一些json方法( https://networkx.github.io/documentation/stable/reference/readwrite/json_graph.html )但似乎没有一个非常适合我的用例。

最合适的方法 - nx.from_dict_of_dicts 但它使用略有不同的dict格式。 它使用的是带有单个“权重”元素的字典,而不是您拥有的权重数字:

{"E": 7} -> {"E": {"weight": 7}}

因此,您需要使用以下代码转换graph dict:

import networkx as nx

graph = {
    "A": {"B": 10, "C": 3},
    "B": {"C": 1, "D": 2},
    "C": {"B": 4, "D": 8, "E": 2},
    "D": {"E": 7},
    "E": {"D": 9}
}

# Convert integer weights to dictionaries with a single 'weight' element
gr = {
    from_: {
        to_: {'weight': w}
        for to_, w in to_nodes.items()
    }
    for from_, to_nodes in graph.items()
}

G = nx.from_dict_of_dicts(gr, create_using=nx.DiGraph)
G.edges.data('weight')

输出:

OutEdgeDataView([
('D', 'E', 7),
('B', 'D', 2),
('B', 'C', 1),
('A', 'B', 10),
('A', 'C', 3),
('C', 'E', 2),
('C', 'B', 4),
('C', 'D', 8),
('E', 'D', 9)
])

PS gr dict看起来像这样:

{'A': {'B': {'weight': 10}, 'C': {'weight': 3}},
 'B': {'C': {'weight': 1}, 'D': {'weight': 2}},
 'C': {'B': {'weight': 4}, 'D': {'weight': 8}, 'E': {'weight': 2}},
 'D': {'E': {'weight': 7}},
 'E': {'D': {'weight': 9}}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM