繁体   English   中英

获取networkx图python中邻居节点的属性

[英]Get the attribute of neighbor node in networkx graph python

我想获取networkx图的相邻节点的属性。

import networkx as nx
G=nx.DiGraph()
G.add_node(10, time = '1PM')
G.add_node(20, time = '5PM')
G.add_node(30, time = '10PM')

G.add_edges_from([(10,20),(20,30)])

我想知道节点 10 或 30 的 20 的属性,节点 20 的 10 的属性。

这就是我开始接近但无法弄清楚的方式。

For node1, node2 in G.nodes(data =True):
    print (G.neighbors(node1)['time'])

有没有办法做到这一点? 我感谢您的帮助。

您可以使用G.neighbors(x)获得节点x的邻居的迭代器。 例如,如果您想知道x的每个邻居的"time"参数,您可以简单地这样做:

for neighbor in G.neighbors(x):
    print(G.nodes[neighbor]["time"])

由于您使用的是DiGraph ,因此只考虑传出边来获取邻居,即:

print(list(G.neighbors(10))) # [20]
print(list(G.neighbors(20))) # [30]
print(list(G.neighbors(30))) # []

相反,在Graph中同时使用传入和传出边:

print(list(G.neighbors(10))) # [20]
print(list(G.neighbors(20))) # [10, 30]
print(list(G.neighbors(30))) # [20]

您可以遍历 DiGraph 中的节点并获取predecessorssuccessors列表。

注意G.neigbors在您的情况下不起作用,因为图形是有向的,它只存储后继列表。

for node in G.nodes:
    try: print('Attribute of {0} from {1}: {2}'.format(node, list(G.predecessors(node))[0], G.node[node]['time']))
    except: pass
    try: print('Attribute of {0} from {1}: {2}'.format(node, list(G.successors(node))[0], G.node[node]['time']))
    except: pass
Attribute of 10 from 20: 1PM
Attribute of 20 from 10: 5PM
Attribute of 20 from 30: 5PM
Attribute of 30 from 20: 10PM

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM