[英]Iterating over dictionary and performing function
目前正在尝试使用模拟退火解决方案解决旅行商问题。 所有点都存储在字典中,点名作为键,坐标作为值。 无法编写遍历给定路径(随机打乱的位置字典)中的每个键的 for 循环(path_tour 函数),计算距离并将值添加到列表中以重新计算总长度。 我下面的当前 function 返回 KeyError,我不知道为什么。
#Calculate distances between points
def point_distance(point_a, point_b):
return math.sqrt((point_a[0] - point_b[0])**2 + (point_a[1] - point_b[1])**2)
def get_distance_matrix(points):
distance_matrix = {}
for location_a in points:
distance_matrix[location_a] = {}
for location_b in points:
distance_matrix[location_a][location_b] = point_distance(
points[location_a], points[location_b])
return distance_matrix
#Calculate length of path
def path_tour(tour):
path_length = 0
distances = get_distance_matrix(tour)
for key, value in tour.items():
path_length += distances[key][key[1:]]
return path_length
正如您从错误中看到的那样,它试图查找关键的“学生信息台”。 我假设位置名称是“Student Information Desk”,所以key[1:]
删除了第一个字母。 这显然不是查找的正确位置。
我猜你想要从当前到下一个旅游地点的距离。 那会是这样的
locations = list(tour.keys())
for first, second in zip(locations[:-1], locations[1:]):
path_length += distances[first][second]
不过,我不明白为什么你的旅行是一本字典。 不应该是一个列表开始吗? 我知道 Python-3 中的字典保持其插入顺序,但这种用法似乎违反直觉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.