如果图的部分是真正不相交的(根据您的小示例),那么考虑使用^{}提取子图。
这只适用于无向图,因此如果您使用的是有向图,则需要先转换为无向图。import networkx as nx
G = nx.DiGraph()
G.add_nodes_from([1,2,3,4])
G.add_edge(1,2)
G.add_edge(3,4)
# make an undirected copy of the digraph
UG = G.to_undirected()
# extract subgraphs
sub_graphs = nx.connected_component_subgraphs(UG)
for i, sg in enumerate(sub_graphs):
print "subgraph {} has {} nodes".format(i, sg.number_of_nodes())
print "\tNodes:", sg.nodes(data=True)
print "\tEdges:", sg.edges()
结果是:subgraph 1 has 2 nodes
Nodes: [(1, {}), (2, {})]
Edges: [(1, 2)]
subgraph 1 has 2 nodes
Nodes: [(3, {}), (4, {})]
Edges: [(3, 4)]
您可以使用子图节点标签对初始图中的数据进行操作sg.nodes()[0] in G
>>> True
阅读EdChum链接的答案,似乎weakly_connected_component_subgraphs()操作有向图,但将其视为无向图,因此保存副本可能是至关重要的。然而,关于这个和相关函数^{}的文档目前有点少。