networkx 通过属性搜索节点

use*_*834 4 python networkx

我寻找更优雅的方法来从以下属性之一搜索有向图中的节点:

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}})
Run Code Online (Sandbox Code Playgroud)

现在我用来g.nodes.data()获取node_id,attrs元组:

def search(g, d, a):
    for nid, attrs in g.nodes.data():
        if attrs.get('d') == d and attrs.get('a') == a:
            return nid

search(g, d=1, a=9)
# 12
Run Code Online (Sandbox Code Playgroud)

el_*_*ldo 6

“更优雅的方式”确实很主观......我提出这两种方法:

[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}}
Run Code Online (Sandbox Code Playgroud)

对于大量数据,过滤功能可能更有效。有趣的是,如果你想在 python 3 中实现 lambda 函数,你需要传递上面的表达式,因为 Python 3 不再支持元组参数解包。在 python 2.7 中,它可能会更优雅:

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}}
Run Code Online (Sandbox Code Playgroud)