如何在打印 Networkx 图的边属性时对边的顺序进行排序

How to sort the order of edges while printing the edge attributes of a Networkx graph

我正在尝试以排序方式打印 Networkx 图的边属性。

例如,

print(sorted(G.edges(data=True))

将显示有序字典

[(3, 7, OrderedDict([('w1', 9.62), ('w2', 37.2)])), (3, 8, OrderedDict([('w1', 9.42), ('w2', 49.6)]))]

同样,我想打印单个属性(仅 w1w2,data=True 打印两者)作为排序输出。

例如,当我尝试

print(sorted(nx.get_edge_attributes(G, 'w1').values()))

无效。

关于如何显示单个属性的排序输出的任何建议都将非常有帮助。

nx.get_edge_attributes 只会 return 实际属性。可能最简单的方法是只保留 G.edges(data=True):

结果中的一个属性
G = nx.Graph()
G.add_edge(3, 8, w1= 9.62, w2=37.2)
G.add_edge(3, 7, w1= 9.42, w2=49.6)

attr = 'w1'
sorted(((*edge, (attr, d[attr])) for *edge, d in G.edges(data=True)))
# [(3, 7, ('w1', 9.42)), (3, 8, ('w1', 9.62))]