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

标签 python graph 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 字典:

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/

相关文章:

python - 类型错误 : unhashable type: 'list' in python

python - NetworkX:将权重复制到新图,权重是重复的

python - Python 中 <- 符号的含义

database-design - 如何为图数据库建模?

graph - 在 Elm 中管理不可能状态的好模式是什么?

algorithm - 计算最大独立集算法的正确性

python - 寻找平面图最小循环基的算法

python - 如何使用 Pandas 将最后一行移到第一行

python - 导入错误 : cannot import name 'InvalidSchemeCombination' from 'pip._internal.exceptions'

python - 如何计算 Pandas 每个时期的增加量