如果图的部分是真正不相交的(就像您的小例子一样),那么请考虑使用connected_component_subgraphs()
提取子图。
这只适用于无向图,所以如果您正在使用有向图,则需要先转换为无向图。
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)
UG = G.to_undirected()
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()
在有向图上运作,但将其视为无向图,因此保存副本可能至关重要。 但是,目前对此及其相关函数weakly_connected_components()
的文档有点简略。
weakly_connected_component_subgraphs
,如果可以的话,这是一个重复的问题:https://dev59.com/qHbZa4cB1Zd3GeqPGoW7 - EdChum