[英]Edge attributes of shortest path using networkx
我正在嘗試使用 networkx 來計算兩個節點之間的最短路徑。 例如:
paths = nx.shortest_path(G, ‘A’, ‘C’, weight=‘cost’)
paths
將返回類似於:['A', 'B', 'C']
nx.shortest_path_length()
返回該路徑的成本,這也很有幫助。 但是,我還想返回為此路徑遍歷的邊列表。 在這些邊緣內是我存儲的其他屬性,我想返回。
這可能嗎?
這是一個可以滿足您所有需要的代碼(希望是:p):
import numpy as np
# import matplotlib.pyplot as plt
import networkx as nx
# Create a random graph with 8 nodes, with degree=3
G = nx.random_regular_graph(3, 8, seed=None)
# Add 'cost' attributes to the edges
for (start, end) in G.edges:
G.edges[start, end]['cost'] = np.random.randint(1,10)
# Find the shortest path from 0 to 7, use 'cost' as weight
sp = nx.shortest_path(G, source=0, target=7, weight='cost')
print("Shortest path: ", sp)
# Create a graph from 'sp'
pathGraph = nx.path_graph(sp) # does not pass edges attributes
# Read attributes from each edge
for ea in pathGraph.edges():
#print from_node, to_node, edge's attributes
print(ea, G.edges[ea[0], ea[1]])
輸出將類似於以下內容:
Shortest path: [0, 5, 7]
(0, 5) {'cost': 2}
(5, 7) {'cost': 3}
該腳本允許您獲取訪問邊緣的屬性列表
import networkx as nx
import matplotlib.pyplot as plt
Nodes = [('A', 'B'),('A', 'C'), ('C', 'D'), ('D', 'B'), ('C', 'B')]
G = nx.Graph()
num = 1 #name edge
for node in Nodes:
G.add_edge(*node, num = num, weight = 1)
num += 1
pos = nx.spring_layout(G)
edge_labels = nx.get_edge_attributes(G, 'num')
nx.draw(G, with_labels=True, node_color='skyblue', pos=pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_color='red')
plt.show()
path = nx.shortest_path(G)
st = 'A' #start node
end = 'D' #end node
path_edges = [edge_labels.get(x, edge_labels.get((x[1],x[0]))) for x in zip(path[st][end], path[st][end][1:])]
print('Path by nodes: ', path[st][end])
print('Path by edges: ', path_edges)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.