遍历字典并执行函数
Iterating over dictionary and performing function
目前正在尝试使用模拟退火解决方案解决旅行商问题。所有的点都存储在字典中,点名作为键,坐标作为值。在编写遍历给定路径(随机打乱位置字典)中的每个键的 for 循环(path_tour 函数)时遇到问题,计算距离并将值添加到列表以重新计算总长度。我当前的函数 returns 有一个 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
how the get_distance_matrix is called
example of a path
error message
正如您从错误中看到的那样,它正在尝试查找关键字“tudent Information Desk”。我假设位置名称是“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 中的词典会保留其插入顺序,但这种用法似乎 counter-intuitive.
目前正在尝试使用模拟退火解决方案解决旅行商问题。所有的点都存储在字典中,点名作为键,坐标作为值。在编写遍历给定路径(随机打乱位置字典)中的每个键的 for 循环(path_tour 函数)时遇到问题,计算距离并将值添加到列表以重新计算总长度。我当前的函数 returns 有一个 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
how the get_distance_matrix is called
example of a path
error message
正如您从错误中看到的那样,它正在尝试查找关键字“tudent Information Desk”。我假设位置名称是“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 中的词典会保留其插入顺序,但这种用法似乎 counter-intuitive.