采用
Graph.subgraph(nodes)
NetworkX 2.x +:
演示版
import networkx as nxG = nx.Graph()G.add_nodes_from([1, 2, 3], color="red")G.add_nodes_from([4, 5, 6])G.nodes # NodeView((1, 2, 3, 4, 5, 6))# create generatornodes = ( node for node, data in G.nodes(data=True) if data.get("color") == "red")subgraph = G.subgraph(nodes)subgraph.nodes # NodeView((1, 2, 3))旧版NetworkX
遍历(
Graph.iter_nodes())并根据您的条件过滤节点。将该列表传递给
Graph.subgraph(),它将返回这些节点及其内部边缘的副本。
例如:
G = nx.Graph()# ... build or do whatever to the graphnodes = (n for n, d in G.nodes_iter(data=True)) if d.get('color') == 'red')subgraph = G.subgraph(nodes)


