【问题标题】:Accessing elements from a list?从列表中访问元素?
【发布时间】:2020-04-11 19:43:32
【问题描述】:

我正在尝试计算两个列表之间的距离,以便找到所有坐标之间的最短距离。

这是我的代码:

import random
import math
import copy

def calculate_distance(starting_x, starting_y, destination_x, destination_y):
    distance = math.hypot(destination_x - starting_x, destination_y - starting_y)  # calculates Euclidean distance (straight-line) distance between two points
    return distance
def nearest_neighbour_algorithm(selected_map):

  temp_map = copy.deepcopy(selected_map)
  optermised_map = [] # we setup an empty optimised list to fill up

  # get last element of temp_map to set as starting point, also removes it from temp_list 
  optermised_map.append(temp_map.pop()) # we set the first element of the temp_map and put it in optimised_map as the starting point and remove this element from the temp_map

  for x in range(len(temp_map)):
    nearest_value = 1000 
    neares_index = 0       
    for i in range(len(temp_map[x])):
      current_value = calculate_distance(*optermised_map[x], *temp_map[x])

我在这部分得到一个错误,我不知道为什么:

    for i in range(len(temp_map[x])):
      current_value = calculate_distance(*optermised_map[x], *temp_map[x])

我试图找出这两个列表之间的点之间的距离,我得到的错误是我的列表索引超出了 for 循环所在的范围

【问题讨论】:

  • 你没有告诉我们错误是什么,我不知道为什么。

标签: python list artificial-intelligence nearest-neighbor


【解决方案1】:

在第一次迭代中,optermised_map 的长度为 1。这可能会导致错误,因为它正在迭代可能大于 1 的 len(temp_map)。我认为您可能想要:

for i in range(len(optermised_map)):
  current_value = calculate_distance(*optermised_map[i], *temp_map[x])

【讨论】:

  • 试过了但没有用,但我确实这样做了:for i in range(len(temp_map)): current_value = calculate_distance(*optermised_map[x], *temp_map[i])
  • optermised_map 列表索引超出范围是否仍会出错​​?你现在的 x 范围是多少?
  • 不,它不会给我一个索引超出范围错误。 x 在 opttermised_map 中的值范围内
【解决方案2】:

列表的长度是否相同?我可能是错的,但这对我来说听起来像是余弦相似度练习。看看这个非常简单的练习。

from scipy import spatial

dataSetI = [3, 45, 7, 2]
dataSetII = [2, 54, 13, 15]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
result
# 0.97228425171235

dataSetI = [1, 2, 3, 10]
dataSetII = [2, 4, 6, 20]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
result
# 1.0

dataSetI = [10, 200, 234, 500]
dataSetII = [45, 3, 19, 20]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
result
# 0.4991255575740505

在第二次迭代中,我们可以看到两个列表中数字的比例完全相同,但数字不同。我们关注数字的比率。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多