在设置networkx.MultiDiGraph实例G的属性值时,我遇到了此错误。我正在使用set_edges_attributions方法。代码如下。
# a lib I wrote myself
import dijkstra
for edge in G.edges():
w = dijkstra.cost_cal(G, edge[0])
print(w, edge)
# G: networkx.MultiDiGraph
# edge: a tuple with two node IDs
# w: float
nx.set_edge_attributes(G, {edge: {"cost": w}})退出:
0.05050505050505051 (1004215022, 1955253358)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [6], in <cell line: 6>()
7 w = dijkstra.cost_cal(G, edge[0])
8 print(w, edge)
----> 9 nx.set_edge_attributes(G, {edge: {"cost": w}})
File C:\ProgramData\Miniconda3\envs\PyGIS\lib\site-packages\networkx\classes\function.py:821, in set_edge_attributes(G, values, name)
818 else:
819 # `values` consists of doct-of-dict {edge: {attr: value}} shape
820 if G.is_multigraph():
--> 821 for (u, v, key), d in values.items():
822 try:
823 G[u][v][key].update(d)
ValueError: not enough values to unpack (expected 3, got 2)发布于 2022-07-03 01:42:17
您没有为set_edge_attributes提供正确的边缘格式。MultiDiGraph边缘由3个值组成,即起始节点、结束节点和键。
示例:
import networkx as nx
G = nx.MultiDiGraph()
G.add_edges_from([('a', 'b'), ('a', 'c'), ('a', 'b')])
print(G.edges)输出:
OutMultiEdgeView([('a', 'b', 0), ('a', 'b', 1), ('a', 'c', 0)])您可以看到,我们有两个a->b边,一个是键0,另一个是键1,所有三个参数都需要唯一地标识边缘。

所以你需要使用:
nx.set_edge_attributes(G, {('a', 'b', 0): {'cost': 42}})但你很可能只使用了:
nx.set_edge_attributes(G, {('a', 'b'): {'cost': 42}})请注意,与G.edges不同,G.edges()没有输出键:
OutMultiEdgeDataView([('a', 'b'), ('a', 'b'), ('a', 'c')])所以在循环中使用G.edges。
https://stackoverflow.com/questions/72843364
复制相似问题