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

如何使用NetworkX返回网络中无外部连接的节点孤岛?

NetworkX获取小节点孤岛的方法

你需要用到连通分量相关的接口,根据你网络的类型选择对应方法即可:

  • 若为无向交通网络:使用nx.connected_components(G),该接口会返回包含所有连通分量的生成器,每个分量对应一个节点集合
  • 若为有向交通网络:忽略边方向判断连通性用nx.weakly_connected_components(G),要求双向可达的强连通性用nx.strongly_connected_components(G)

筛选2-5个节点的孤岛代码示例

以无向图为例,筛选符合节点数量要求的孤岛,返回列表格式,每个元素为对应孤岛的节点集合:

import networkx as nx

# 直接筛选节点数为2-5的所有连通分量
small_islands = [comp for comp in nx.connected_components(G) if 2 <= len(comp) <= 5]

如果需要额外排除主网络(最大连通分量),可以增加过滤条件:

all_comps = list(nx.connected_components(G))
max_comp_size = max(len(c) for c in all_comps)
# 排除主网络后筛选2-5节点的孤岛
small_islands = [comp for comp in all_comps if 2 <= len(comp) <=5 and len(comp) != max_comp_size]

有向图场景只需把上述代码中的连通分量接口替换为对应接口即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:39:02