networkx通过属性搜索节点 [英] networkx search for a node by attributes
问题描述
我正在寻找一种更高级的方法来从以下属性中搜索DiGraph中的节点:
I look for the more elegent way to search for a node in a DiGraph from o ne of this attributes::
g = nx.DiGraph()
g.add_nodes_from([(1, dict(d=0, a=7)), (2, dict(d=0, a=6))])
g.add_nodes_from([(11, dict(d=1, a=4)), (12, dict(d=1, a=9))])
g.add_nodes_from([(21, dict(d=1, a=4)), (121, dict(d=2, a=7))])
g.add_edges_from([(1, 11), (1, 12), (2, 21), (12, 121)])
g.nodes.data()
# NodeDataView({1: {'d': 0, 'a': 7}, 2: {'d': 0, 'a': 6},
# 11: {'d': 1, 'a': 4}, 12: {'d': 1, 'a': 9},
# 21: {'d': 1, 'a': 4}, 121: {'d': 2, 'a': 7}})
现在我使用g.node.data()
来获取node_id和attrs元组:
For now I use g.node.data()
to get node_id, attrs tuple:
def search(g, d, a):
for nid, attrs in g.node.data():
if attrs.get('d') == d and attrs.get('a') == a:
return nid
search(g, d=1, a=9)
# 12
推荐答案
一种更优雅的方式"真的很主观...我提出了两种方法:
"A more elegant way" is really subjective... I propose these two approaches:
[x for x,y in g.nodes(data=True) if y['d']==1 and y['a'] == 9]
#[12]
dict(filter(lambda x: x[0] if x[1]['a'] == 9 and x[1]['d'] == 1 else False, g.nodes(data=True)))
#{12: {'a': 9, 'd': 1}}
过滤器功能可能在处理大量数据时更为有效.有趣的是,如果要在python 3中实现lambda函数,则需要通过上面的表达式,就像在Python 3中不再支持元组参数解包一样.在python 2.7中,它可能更优雅:
Probably the filter function is more efficient with large amount of data. Interestingly, if you want to implement the lambda function in python 3 you need to pass through the expression above as in Python 3 tuple parameter unpacking is not supported anymore. In python 2.7 it could be probably more elegant:
dict(filter(lambda (x,y): x if y['a'] == 9 and y['d'] == 1 else False, g.nodes(data=True)))
#{12: {'a': 9, 'd': 1}}
这篇关于networkx通过属性搜索节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!