使用networkx的最短路径的边缘属性

时间:2019-08-27 23:29:53

标签: python networkx

我正在尝试使用networkx计算两个节点之间的最短路径。例如:

paths = nx.shortest_path(G, ‘A’, ‘C’, weight=‘cost’)

paths将返回以下内容: [‘A’,‘B’,‘C’]

nx.shortest_path_length()返回该路径的成本,这也很有帮助。但是,我也想返回该路径所经过的边的列表。在这些边缘内是我要返回的其他存储属性。

这可能吗?

2 个答案:

答案 0 :(得分:0)

这是可以满足您所有需求的代码(希望: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}

答案 1 :(得分:0)

该脚本允许您获取已访问边的属性列表

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)