如何导出无向图连通分量节点及其属性?
导出带节点属性的连通分量并按属性分类展示
核心思路
先通过NetworkX获取无向图的所有连通分量,提取每个分量中节点的完整属性,再根据指定属性(Category/Weight/Color)对节点进行分组展示或导出。
1. 获取连通分量与节点属性
遍历所有连通分量,为每个分量收集节点ID及对应属性,生成结构化数据:
import networkx as nx # 替换为你的实际无向图G G = nx.Graph() # 示例节点与属性 G.add_nodes_from([ (1, {"Category": "A", "Weight": 10, "Color": "red"}), (2, {"Category": "A", "Weight": 20, "Color": "blue"}), (3, {"Category": "B", "Weight": 15, "Color": "red"}), (4, {"Category": "B", "Weight": 25, "Color": "green"}), (5, {"Category": "C", "Weight": 30, "Color": "blue"}) ]) # 获取所有连通分量集合 connected_components = list(nx.connected_components(G)) # 构建带属性的连通分量数据 components_with_attrs = [] for comp_idx, nodes in enumerate(connected_components, start=1): component_info = { "component_id": comp_idx, "nodes": [{"node_id": n, **G.nodes[n]} for n in nodes] } components_with_attrs.append(component_info)
2. 按指定属性分类展示
根据需求选择Category/Weight/Color作为分类键,将同属性节点按连通分量归类展示:
按Category分类
# 按Category分组 category_groups = {} for comp in components_with_attrs: for node in comp["nodes"]: cat = node["Category"] if cat not in category_groups: category_groups[cat] = [] category_groups[cat].append({ "component_id": comp["component_id"], "node_id": node["node_id"], "Weight": node["Weight"], "Color": node["Color"] }) # 打印分类结果 print("=== 按Category分类结果 ===") for category, node_list in category_groups.items(): print(f"\n*类别: {category}*") for item in node_list: print(f"- 连通分量ID: {item['component_id']}, 节点ID: {item['node_id']}, 权重: {item['Weight']}, 颜色: {item['Color']}")
按Weight/Color分类
只需将上述代码中的node["Category"]替换为node["Weight"]或node["Color"],即可实现对应属性的分类展示。
3. 导出结构化数据(可选)
如果需要持久化数据,可将结果导出为JSON格式:
import json # 导出带属性的连通分量原始数据 with open("components_with_attributes.json", "w", encoding="utf-8") as f: json.dump(components_with_attrs, f, indent=4, ensure_ascii=False) # 导出按Category分类的数据 with open("category_grouped_components.json", "w", encoding="utf-8") as f: json.dump(category_groups, f, indent=4, ensure_ascii=False)
内容的提问来源于stack exchange,提问作者nplusone
相关产品推荐
相关产品推荐

