Cur*_*tLH 3 python for-loop networkx
我有一个非常大的无向网络加载到graph()由许多断开连接的组件组成的NetworkX 中。我还将一组感兴趣的节点加载到一组中。我想浏览所有提取的所有组件,其中至少包含感兴趣的节点之一。
# create empty graph
g = nx.Graph()
# add edges to the graph
g.add_edges_from([['a','b'],['a','c'],['b','c'],['d','e'],['e','f'],['d','f'],['g','h'],['g','i'],['h','i']])
# load nodes of interest into a set
interest_nodes = set(['a', 'b', 'f'])
# number of connected components
nx.number_connected_components(g)
# loop through each connected component and add all of the edges for that component to a list if a node in that component is found in the interest_nodes
interest_edges = []
for i in nx.connected_component_subgraph(g):
for u in i.edges():
if u in interest_nodes:
interest_edges.append(u)
Run Code Online (Sandbox Code Playgroud)
但是,我返回一个空列表。
理想情况下,我想返回一个列表,其中包含任何连接的组件中的所有边,该组件中至少包含集合中的一个节点interest_nodes。我应该在下面找回什么,但我什么也没找回来。
interest_edges = [('a', 'c'),
('a', 'b'),
('c', 'b'),
('e', 'd'),
('e', 'f'),
('d', 'f')]
Run Code Online (Sandbox Code Playgroud)
你近了 最简单的方法是通过检查集合交点的长度来检查每个组件,以查看节点集是否重叠。
import networkx as nx
g = nx.Graph([['a','b'],['a','c'],['b','c'],['d','e'],['e','f'],['d','f'],['g','h'],['g','i'],['h','i']])
interest_nodes = set(['a', 'b', 'f'])
interest_edges = []
for component in nx.connected_component_subgraphs(g):
if len(set(component) & interest_nodes) > 0:
interest_edges.extend(component.edges())
print interest_edges
# output
# [('a', 'c'), ('a', 'b'), ('c', 'b'), ('e', 'd'), ('e', 'f'), ('d', 'f')]
Run Code Online (Sandbox Code Playgroud)