Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用networkx的最短路径的边属性_Python_Networkx - Fatal编程技术网

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

Python 使用networkx的最短路径的边属性,python,networkx,Python,Networkx,我正在尝试使用networkx计算两个节点之间的最短路径。例如: paths = nx.shortest_path(G, ‘A’, ‘C’, weight=‘cost’) 路径将返回如下内容: ['A','B','C'] nx.shortest\u path\u length()返回该路径的成本,这也很有用。不过,我还想返回一个为此路径遍历的边的列表。在这些边中是我存储的其他属性,我想返回这些属性 这可能吗?这里有一个代码,可以满足您的所有需要(希望是:p): 输出将类似于以下内容: Shor

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

paths = nx.shortest_path(G, ‘A’, ‘C’, weight=‘cost’)
路径
将返回如下内容: ['A','B','C']

nx.shortest\u path\u length()
返回该路径的成本,这也很有用。不过,我还想返回一个为此路径遍历的边的列表。在这些边中是我存储的其他属性,我想返回这些属性


这可能吗?

这里有一个代码,可以满足您的所有需要(希望是:p):

输出将类似于以下内容:

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)

不鼓励只使用代码的答案。请提供您的答案如何解决问题的摘要,以及为什么它可能比提供的其他答案更可取。
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)