使用NetworkX/OSMnx查询单起点多终点最短路径报错求助
单起点到多终点的最短路径查询(NetworkX/OSMnx)
你遇到的ValueError是因为ox.distance.shortest_path要求起点和终点参数必须同时为可迭代对象(如列表)或同时为单个值,你当前传入单个起点+列表终点的组合不符合参数规则。
以下是两种可行的解决方法:
方法1:循环遍历逐个计算路径
适合终点数量较少的场景,逻辑直观:
orig_node = ox.nearest_nodes(G, orig_x, orig_y) dest_nodes = ox.nearest_nodes(G, dest_x, dest_y) # 用字典存储每个终点对应的最短路径 routes = {} for dest in dest_nodes: route = ox.distance.shortest_path(G, orig_node, dest, weight='length') routes[dest] = route
方法2:使用NetworkX原生函数(更高效)
OSMnx生成的图本质是NetworkX图,可直接调用NetworkX的shortest_path,它原生支持单起点+多终点的参数组合:
import networkx as nx orig_node = ox.nearest_nodes(G, orig_x, orig_y) dest_nodes = ox.nearest_nodes(G, dest_x, dest_y) # 一次性获取单起点到所有终点的最短路径 routes = nx.shortest_path(G, source=orig_node, target=dest_nodes, weight='length')
如果只需要路径长度而非具体路径节点序列,可替换为nx.shortest_path_length函数,用法逻辑一致。
内容的提问来源于stack exchange,提问作者elrhmo
相关产品推荐
相关产品推荐

