NetworkX component functions return Python generators. You can create a list of elements in a generator using the Python function list. Here is an example showing this, as well as finding the largest loosely coupled component.
In [1]: import networkx as nx
In [2]: G = nx.DiGraph()
In [3]: G.add_path([1,2,3,4])
In [4]: G.add_path([10,11,12])
You can use for example. to include the generator in the list of subgraphs:
In [5]: list(nx.weakly_connected_component_subgraphs(G))
Out[5]:
[<networkx.classes.digraph.DiGraph at 0x278bc10>,
<networkx.classes.digraph.DiGraph at 0x278ba90>]
The max operator takes a key argument that you can specify for a Python function lenthat calls len (g) on each subgraph to calculate the number of nodes. Thus, to get the component with the most nodes, you can write
In [6]: largest = max(nx.weakly_connected_component_subgraphs(G),key=len)
In [7]: largest.nodes()
Out[7]: [1, 2, 3, 4]
In [8]: largest.edges()
Out[8]: [(1, 2), (2, 3), (3, 4)]
source
share