gpt4 book ai didi

python-3.x - 如何总结 networkx 图边权重?

转载 作者:行者123 更新时间:2023-12-05 06:04:48 25 4
gpt4 key购买 nike

我正在从事 networkx 图形项目。我的任务之一是找出两个节点之间的最短路径并求和权重。如您所见,我可以找到最短路径。但是,我不知道如何总结最短路径中每条边的权重。我认为包中会有一个简单的功能,但我没有找到。 enter image description here

import matplotlib.pyplot as plt
import networkx as nx

def graph(path):
G = nx.Graph()
for line in open(path):
strlist = line.split(',')
n1 = strlist[0].replace('.0', '')
n2 = strlist[1].replace('.0', '')
weight = round(float(strlist[2]), 2)
G.add_weighted_edges_from([(n1, n2, weight)])

# labels = dict((i, i) for i in G.nodes())
# nx.draw_networkx_labels(G, pos=nx.spring_layout(G), labels=labels)
# plt.savefig(filename)
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]
pos = nx.spring_layout(G)
# nodes
nx.draw_networkx_nodes(G, pos, node_size=200, node_color='#ff0000', alpha=0.9)
# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=1, edge_color='b', alpha=0.05)
nx.draw_networkx_edges(G, pos, edgelist=esmall, width=1, edge_color='b', alpha=0.3)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_labels(G, pos, font_size=10, font_family="sans-serif")
nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8, font_family='sans-serif')
plt.axis("off")
plt.show()
return G
G = graph('graph.csv')


shortest_value = nx.shortest_path_length(G, source='210', target='2771')
print(shortest_value)
shortest_path = nx.shortest_path(G, source='210', target='2771', method='dijkstra')
print('shortest path:{}'.format(shortest_path))
print('distance:{}'.format(shortest_value))

最佳答案

使用networkx.Graph.size .

来自示例:

>>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> G.size()
2
>>> G.size(weight="weight")
6.0

关于python-3.x - 如何总结 networkx 图边权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66217836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com