我有一个NetworkX图,各种节点属性都加载到图中。我想迭代这个图,首先找到包含属性'metric' : 'Top2'
的所有节点。然后,一旦我有了这个列表,我想要所有'Top2'节点的边缘,并列出'Top2'节点对具有属性'city': 'Dallas'
'的节点的任何边缘
我能够将我的图形和属性成功加载到NetworkX中,但我似乎无法弄清楚如何让节点属性过滤部分像我想的那样弄清楚。
最终,我想找到任何连接,其中具有属性'Top2'的节点与具有属性'Dallas'的节点直接接触:
代码
# import module
import networkx as nx
# create a blank graph
g = nx.Graph()
# add nodes with attributes to the graph
n = [(u'A', {'city': 'Dallas'}),
(u'C', {'city': 'Toledo'}),
(u'B', {'city': 'Dallas'}),
(u'E', {'city': 'Toldeo'}),
(u'D', {'city': 'Lousiville', 'metric': 'Top2'}),
(u'G', {'city': 'Lousiville'}),
(u'F', {'city': 'Dallas', 'metric': 'Top2'})]
e = [(u'A', u'B'),
(u'C', u'B'),
(u'B', u'D'),
(u'E', u'D'),
(u'E', u'G'),
(u'E', u'F'),
(u'D', u'G'),
(u'D', u'F'),
(u'G', u'F')]
# add nodes and edges to the graph
g.add_nodes_from(n)
g.add_edges_from(e)
# draw the graph
nx.draw(g)
# iterate through graph to identify all nodes with attribute 'metric' == 'Top2'
Top2_nodes = []
for n in g.nodes(data=True) if n[1]['metric'] == 'Top2'
Top2_nodes.append(n)
# iterate through 'Top2_nodes' to identify their connections to nodes with attribute 'city': 'Dallas'
...
理想情况下,结果的格式如下:
D,B
D,F
D,G
答案 0 :(得分:1)
这使用了两个返回bool的辅助函数。您的实际结果最终将作为列表理解返回。
nodes = g.node
def has_top2(n):
return 'metric' in nodes[n] and nodes[n]['metric'] == 'Top2'
def has_dallas(n):
return 'city' in nodes[n] and nodes[n]['city'] == 'Dallas'
[(n, u) for n, u in g.edges()
if (has_top2(n) and has_dallas(u))
or (has_top2(u) and has_dallas(n))
]