【发布时间】:2026-01-04 08:20:03
【问题描述】:
所以我正在创建一个代码来使用 networkx 计算最短路径。我使用 numpy 创建了一个 3D 数组,然后像这样计算最短路径:
import numpy as np
import networkx as nx
arr = np.random.randint(1, 100, size = (2, 5, 5)) #3D array
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
print(path)
由于我使用的是两个矩阵,我得到了下一个输出:
[0, 1, 3] #path1
[0, 3] #path2
之后我决定创建一个函数来做同样的事情,就像这样:
import numpy as np
import networkx as nx
arr = np.random.randint(1, 100, size = (2, 5, 5)) #3D array
def shortest(prices):
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
return path
print(shortest(arr))
我得到了下一个输出:
[0, 1, 3] #same as path 1
如果我像这样改变“返回路径”的位置:
def shortest(precios):
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
return path
print(shortest(arr))
我得到了下一个输出:
[0, 3] #same as path 2
我无法使用我的函数在同一输出中获取两条路径。知道这里发生了什么吗?我正在练习在 python 中使用函数,因为我对这个主题有点陌生,所以我希望你能帮助我看看有什么问题?谢谢!
【问题讨论】:
标签: python function numpy for-loop networkx