ToB企服应用市场:ToB评测及商务社交产业平台

标题: [Python图论]在用图nx.shortest_path求解最短路径时,节点之间有多条边edge [打印本页]

作者: 去皮卡多    时间: 2024-9-5 10:01
标题: [Python图论]在用图nx.shortest_path求解最短路径时,节点之间有多条边edge
问: 在利用图求最短路径时,如果节点之间有多条路径,shortest_route = nx.shortest_path(G, source=start_node, target=end_node, weight='length')会如那里理,会自动选择最短那条吗?
  1. # 输出图G各节点之间有多少条边edge,并给出其长度
  2. Edges between 103928 and 25508583:共2条
  3. Edge: 103928 -> 25508583, Key: 0, Length: 77.277
  4. Edge: 103928 -> 25508583, Key: 1, Length: 112.16900000000001
  5. Edges between 26630792 and 5521427550:共2条
  6. Edge: 26630792 -> 5521427550, Key: 0, Length: 85.091
  7. Edge: 26630792 -> 5521427550, Key: 1, Length: 88.07600000000001
  8. Edges between 107876 and 107873:共2条
  9. Edge: 107876 -> 107873, Key: 0, Length: 83.102
  10. Edge: 107876 -> 107873, Key: 1, Length: 186.669
复制代码
答:是的,nx.shortest_path 会自动选择权重最小的那条路径。
当你在 NetworkX 中利用 nx.shortest_path(G, source=start_node, target=end_node, weight='length') 时,它会根据你指定的权重(在这个例子中是 'length')找到源节点和目标节点之间权重最小的路径。
对于节点之间有多条路径的情况,NetworkX 会如下处理:

具体示例

以你的数据为例:
总结


输出图内各节点之间的边及其长度 代码:
  1. # 输出图内各节点之间的边及其长度
  2. import networkx as nx
  3. # Get all the nodes in the graph
  4. nodes = G.nodes()
  5. # Iterate over all pairs of nodes
  6. for u in nodes:
  7.     for v in nodes:
  8.         # Skip if u and v are the same node
  9.         if u == v:
  10.             continue
  11.         # Get the edges between u and v
  12.         edges = G.get_edge_data(u, v)
  13.         
  14.         # If there are no edges between u and v, skip to the next pair of nodes
  15.         if edges is None:
  16.             continue
  17.         edges_count = len(edges.items())
  18.         if edges_count >1:
  19.           # Print the edges and their lengths
  20.           print(f"Edges between {u} and {v}:共{edges_count}条")
  21.           for key, data in edges.items():
  22.               print(f"Edge: {u} -> {v}, Key: {key}, Length: {data['length']}")
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4