[英]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 中的節點並獲取predecessors
和successors
列表。
注意: 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.