如何检查Graph节点的邻居中是否存在值?

时间:2019-09-22 17:22:51

标签: python networkx

我可以检查图中所有节点的属性中是否存在值:

G = nx.star_graph(4)
nx.set_node_attributes(G, {0:{"x":"a"}, 1:{"x":"b"}, 3:{"x":"a"}, 4:{"x":"b"}})
print(G.nodes(data = "x"))
# [(0, 'a'), (1, 'b'), (2, None), (3, 'a'), (4, 'b')]

print("a" in dict(G.nodes(data = "x")).values())
# True

print("c" in dict(G.nodes(data = "x")).values())
# False

现在,我想检查"x"属性的值是否存在于节点的任何邻居中,例如节点0或节点1

我不知道如何使用访问节点邻居的常用方法来做到这一点。我在想像G[n].nodes(data = "x")之类的东西,但是G[n]返回的AtlasView无法(据我所知)无法访问邻居数据。

G.neighbors(n)返回一个迭代器。我可以只使用此迭代器并逐步检查每个节点的数据。我假设(也许是不正确的)这比“一次”检查所有节点的数据效率低,如上图所示。

答案不一定要遵循我的想法,特别是如果提出的答案更快或更Pythonic。

1 个答案:

答案 0 :(得分:0)

在此处给出类似问题的答案:networkx search for a node by attributes

我想说的答案可能是这样的:

>>> [y for y in [x for x in G[0]] if 'x' in G.node[y]]
[1, 3, 4]
>>> [y for y in [x for x in G[0]] if 'x' in G.node[y] and G.node[y]['x']=='a']
[3]
>>> [y for y in [x for x in G[0]] if 'x' in G.node[y] and G.node[y]['x']=='c']
[]
>>> [y for y in [x for x in G[0]] if 'x' in G.node[y] and G.node[y]['x']=='b']
[1, 4]

我不知道它是多么的“ pythonic”,但是似乎没有一种方便的方法可以访问具有某些标准的邻居。