我已经编写了此功能。它采用索引序列和值矩阵。例如,
path=[1, 0, 2]
matr = [[1, 2, 3], [0, 3, 5], [1, 10, 1]]
这意味着我们的距离为m[1][0]+m[0][2]
= 0 + 3 = 3。
我有要按距离排序的路径列表。如果需要材料价值怎么办?我尝试这样做:list_of_paths.sort(key=distance(matr))
def distance(path, matr):
dist = 0
for i in range(len(path)-1):
dist += matr[path[i]][path[i+1]]
return dist
答案 0 :(得分:1)
您可以使用自定义函数中内置的path
来排序zip()
列表:
def distance(p):
matr = [[1, 2, 3], [0, 3, 5], [1, 10, 1]]
s = 0
for x, y in zip(p, p[1:]):
s += matr[x][y]
return s
path = [[1, 0, 2], [0, 2, 1], [0, 0, 0]]
print(sorted(path, key=distance))
# [[0, 0, 0], [1, 0, 2], [0, 2, 1]] <- Output
# 2 3 13 <- in the increasing order of distance.
答案 1 :(得分:0)
def distance(path):
# matr available from global name space
return sum([matr[path[i]][path[i+1]] for i in range(len(path)-1)])
matr = [[1, 2, 3], [0, 3, 5], [1, 10, 1]]
list_of_paths =[[1, 2, 0], [1, 0, 2], [0, 1, 2]]
list_of_paths.sort(key=distance)
print(list_of_paths)
结果:[[1、0、2],[1、2、0],[0、1、2]]