gpt4 book ai didi

python - 带 Python Networkx 的加权邻接列表

转载 作者:行者123 更新时间:2023-11-28 16:56:26 28 4
gpt4 key购买 nike

我有一个使用以下结构在 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 字典:

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

P.S. gr 字典看起来像这样:

{'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}}}

关于python - 带 Python Networkx 的加权邻接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57886824/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com