获取包含一定数量节点的networkx子图

我有一个 networkx 有向图,我想提取包含一定数量节点的子图。例如,有向图是 0-1-2-3-4-5。我想获取所有包含3个节点的子图。结果应该是:0-1-2、1-2-3、2-3-4、3-4-5。我怎样才能做到这一点?



狐的传说
浏览 199回答 1
1回答

素胚勾勒不出你

我不完全确定我是否理解正确:你的例子意味着你只想要连接的子图?在有向图中,存在不止一种连接(弱连接和强连接)。因此,您必须决定要寻找哪一个。这可能有效:import networkx as nxfrom itertools import combinations# The graph in your example (as I understand it)G = nx.DiGraph((i, i+1) for i in range(5))num_of_nodes = 3 # Number of nodes in the subgraphs (here 3, as in your example)subgraphs = [] # List for collecting the required subgraphsfor nodes in combinations(G.nodes, num_of_nodes):    G_sub = G.subgraph(nodes) # Create subgraph induced by nodes    # Check for weak connectivity    if nx.is_weakly_connected(G_sub):        subgraphs.append(G_sub)combinations(G.nodes, num_of_nodes)迭代num_of_nodes来自 的许多节点的所有唯一组合G。所选的子图正是您提到的:print([H.nodes for H in subgraphs])print([H.edges for H in subgraphs])节目[NodeView((0, 1, 2)), NodeView((1, 2, 3)), NodeView((2, 3, 4)), NodeView((3, 4, 5))][OutEdgeView([(0, 1), (1, 2)]), OutEdgeView([(1, 2), (2, 3)]), OutEdgeView([(2, 3), (3, 4)]), OutEdgeView([(3, 4), (4, 5)])]如果你的图表是G = nx.DiGraph([(i, i+1) for i in range(5)] + [(i+1, i) for i in range(5)])如果您正在寻找强大的连接性,那么您必须使用...    # Check for strong connectivity    if nx.is_strongly_connected(G_sub):        ...(通常的警告:G.subgraph()只给你一个视图。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python