You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Networkx:如何计算有向图中弱连通分量的平均最短路径长度?

问题原因

nx.average_shortest_path_length处理有向图时,默认要求图是强连通的(任意两个节点间存在双向有向路径)。你提取的弱连通子图仅在无向意义上连通,有向结构中可能存在节点对之间无可达路径,因此触发报错。

解决方案

方法一:使用内置参数忽略不可达节点对

直接给average_shortest_path_length添加ignore_unreachable=True参数,让函数只计算存在路径的节点对的平均长度:

wcc_subs = (G.subgraph(c) for c in nx.weakly_connected_components(G))
G_wc = max(wcc_subs, key=len) # 最大弱连通子图
shortest_wc = nx.average_shortest_path_length(G_wc, ignore_unreachable=True)
print(shortest_wc)

方法二:手动遍历计算(更灵活)

如果需要自定义规则(比如排除节点到自身的路径),可以手动遍历所有节点对统计:

wcc_subs = (G.subgraph(c) for c in nx.weakly_connected_components(G))
G_wc = max(wcc_subs, key=len)

total_length = 0
valid_pairs = 0

for u in G_wc.nodes():
    path_lengths = nx.single_source_shortest_path_length(G_wc, u)
    for v, length in path_lengths.items():
        if u != v:  # 跳过节点到自身的路径
            total_length += length
            valid_pairs += 1

average_length = total_length / valid_pairs if valid_pairs > 0 else 0
print(average_length)

可选:转为无向图计算

若需求是无向意义上的平均最短路径,可先将有向子图转为无向图(注意会改变原始结构):

wcc_subs = (G.subgraph(c) for c in nx.weakly_connected_components(G))
G_wc = max(wcc_subs, key=len)
G_undirected = G_wc.to_undirected()
shortest_wc = nx.average_shortest_path_length(G_undirected)
print(shortest_wc)

内容的提问来源于stack exchange,提问作者Jayraj Vakil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:12:58