Python Networkx:获取\u边缘\u数据,ca时返回意外结果;多有向图

Python Networkx:获取\u边缘\u数据,ca时返回意外结果;多有向图,python,networkx,Python,Networkx,我正在使用Python流行的网络库networkx。从下面的代码中,我希望打印的语句是等效的 import networkx as nx graph = nx.Graph() mgraph = nx.MultiDiGraph() for G in [graph, mgraph]: G.add_edge(1, 2, weight=4.7) print(graph.get_edge_data(1, 2)) print(mgraph.get_edge_data(1,2)) 然而,我获

我正在使用Python流行的网络库
networkx
。从下面的代码中,我希望打印的语句是等效的

import networkx as nx

graph = nx.Graph()
mgraph =  nx.MultiDiGraph()

for G in [graph, mgraph]:
    G.add_edge(1, 2, weight=4.7)

print(graph.get_edge_data(1, 2))
print(mgraph.get_edge_data(1,2))
然而,我获得以下信息:

{'weight': 4.7}
{0: {'weight': 4.7}}

对于多向图,为什么要添加额外的
0
键?它对应于什么?

A
multi-digraph
允许多条边。每个边都可能有自己的属性。在您的示例中,它告诉您的是,在
图形
的情况下,边(只能有一条边)的权重为4.7。但是在
多向图
的情况下,它告诉你索引为0的边(碰巧只有这条边)的权重为4.7

尝试此操作以获得更清晰的效果,再次添加边缘,但权重不同:

import networkx as nx

graph = nx.Graph()
mgraph =  nx.MultiDiGraph()

for G in [graph, mgraph]:
    G.add_edge(1, 2, weight=4.7)
    G.add_edge(1, 2, weight = 5)  #are we overwriting an edge, or adding an extra edge?

print(graph.get_edge_data(1, 2))
print(mgraph.get_edge_data(1,2))
它给出了输出

>{'weight': 5}
>{0: {'weight': 4.7}, 1: {'weight': 5}}
显示在
图形
情况下,边属性被覆盖(因为只有一条边),但在
多向图
情况下,第二条边添加了索引
1