您可能有一个networkx MultiGraph而不是一个图形,在这种情况下,边的属性设置有些麻烦。(您可以通过加载在节点之间具有多个边的图来获得多图)。您可能在G.edge[id_source][id_target]['type']= value
需要时 通过分配属性来破坏数据结构 G.edge[id_source][id_target][key]['type']= value
。
这是有关图和多图的工作方式不同的示例。
对于Graph case属性,其工作方式如下:
In [1]: import networkx as nx
In [2]: G = nx.Graph()
In [3]: G.add_edge(1,2,color='red')
In [4]: G.edges(data=True)
Out[4]: [(1, 2, {'color': 'red'})]
In [5]: G.add_edge(1,2,color='blue')
In [6]: G.edges(data=True)
Out[6]: [(1, 2, {'color': 'blue'})]
In [7]: G[1][2]
Out[7]: {'color': 'blue'}
In [8]: G[1][2]['color']='green'
In [9]: G.edges(data=True)
Out[9]: [(1, 2, {'color': 'green'})]
使用MultiGraphs时,还有一个附加级别的键可以跟踪平行边缘,因此其工作原理有所不同。如果未显式设置键,则MultiGraph.add_edge()将使用内部选择的键(顺序整数)添加一个新边。
In [1]: import networkx as nx
In [2]: G = nx.MultiGraph()
In [3]: G.add_edge(1,2,color='red')
In [4]: G.edges(data=True)
Out[4]: [(1, 2, {'color': 'red'})]
In [5]: G.add_edge(1,2,color='blue')
In [6]: G.edges(data=True)
Out[6]: [(1, 2, {'color': 'red'}), (1, 2, {'color': 'blue'})]
In [7]: G.edges(data=True,keys=True)
Out[7]: [(1, 2, 0, {'color': 'red'}), (1, 2, 1, {'color': 'blue'})]
In [8]: G.add_edge(1,2,key=0,color='blue')
In [9]: G.edges(data=True,keys=True)
Out[9]: [(1, 2, 0, {'color': 'blue'}), (1, 2, 1, {'color': 'blue'})]
In [10]: G[1][2]
Out[10]: {0: {'color': 'blue'}, 1: {'color': 'blue'}}
In [11]: G[1][2][0]['color']='green'
In [12]: G.edges(data=True,keys=True)
Out[12]: [(1, 2, 0, {'color': 'green'}), (1, 2, 1, {'color': 'blue'})]