networkx search for a node by attributes

风流意气都作罢 提交于 2020-05-17 07:29:04

问题


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}})

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

回答1:


"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}}

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}}


来源:https://stackoverflow.com/questions/50447951/networkx-search-for-a-node-by-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!