This documents the development version of NetworkX. Documentation for the current release can be found here.
subgraph_view(G, filter_node=<function no_filter>, filter_edge=<function no_filter>)¶
Gapplying a filter on nodes and edges.
subgraph_viewprovides a read-only view of the input graph that excludes nodes and edges based on the outcome of two filter functions
filter_edgefunction takes two (or three arguments if
Gis a multi-graph) — the nodes describing an edge, plus the edge-key if parallel edges are possible — and returns
Trueif the edge should be included in the subgraph, and
Falseif it should not be included.
Both node and edge filter functions are called on graph elements as they are queried, meaning there is no up-front cost to creating the view.
A directed/undirected graph/multigraph
- filter_nodecallable, optional
A function taking a node as input, which returns
Trueif the node should appear in the view.
- filter_edgecallable, optional
A function taking as input the two nodes describing an edge (plus the edge-key if
Gis a multi-graph), which returns
Trueif the edge should appear in the view.
A read-only graph view of the input graph.
>>> G = nx.path_graph(6)
Filter functions operate on the node, and return
Trueif the node should appear in the view:
>>> def filter_node(n1): ... return n1 != 5 ... >>> view = nx.subgraph_view(G, filter_node=filter_node) >>> view.nodes() NodeView((0, 1, 2, 3, 4))
We can use a closure pattern to filter graph elements based on additional data — for example, filtering on edge data attached to the graph:
>>> G["cross_me"] = False >>> def filter_edge(n1, n2): ... return G[n1][n2].get("cross_me", True) ... >>> view = nx.subgraph_view(G, filter_edge=filter_edge) >>> view.edges() EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
>>> view = nx.subgraph_view(G, filter_node=filter_node, filter_edge=filter_edge,) >>> view.nodes() NodeView((0, 1, 2, 3, 4)) >>> view.edges() EdgeView([(0, 1), (1, 2), (2, 3)])