简体   繁体   English

从列表中访问元素?

[英]Accessing elements from a list?

I am trying to calculate the distance between two lists so I can find the shortest distance between all coordinates.我正在尝试计算两个列表之间的距离,以便找到所有坐标之间的最短距离。

Here is my code:这是我的代码:

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])

I get an error at this part and im not sure why:我在这部分得到一个错误,我不知道为什么:

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

I am trying to find the distance between points between these two lists and the error I get is that my list index is out of range where the for loop is我试图找到这两个列表之间的点之间的距离,我得到的错误是我的列表索引超出了 for 循环所在的范围

On the first iteration optermised_map would be length 1. This would likely cause the error because it's iterating over len(temp_map) which is likely more than 1. I think you may have wanted:在第一次迭代中, optermised_map 的长度为 1。这可能会导致错误,因为它正在迭代可能超过 1 的 len(temp_map)。我认为您可能想要:

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

Are the lengths of the lists the same?列表的长度是否相同? I could be wrong, but this sounds like a cosine similarity exercise to me.我可能是错的,但这对我来说听起来像是余弦相似度练习。 Check out this very simple exercise.看看这个非常简单的练习。

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

In the second iteration, we can see that the ratios of the numbers in the two lists are exactly the same, but the numbers are different.在第二次迭代中,我们可以看到两个列表中数字的比例完全相同,但数字不同。 We focus in the ratios of the numbers.我们关注数字的比率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM