如何遍历坐标列表并计算它们之间的距离?

How to iterate through a list of coordinates and calculate distance between them?

在列表中,存在具有 x 和 y 值的坐标。

[(7, 9), (3, 3), (6, 0), (7, 9)]

我可以计算两点之间的距离。

distance_formula = math.sqrt(((x[j]-x[i])**2)+((y[j]-y[i])**2))

我很难浏览列表并计算每个点之间的距离。我想计算第一个索引和第二个索引、第二个索引和第三个索引、第三个索引和第四个索引之间的距离...

您可以使用 zip() 做到这一点。 zip() 将生成坐标对并让您方便地遍历它们。

coordinates = [(7, 9), (3, 3), (6, 0), (7, 9)]

for (x1, y1), (x2, y2) in zip(coordinates, coordinates[1:]):
    distance_formula = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
    print(distance_formula)

有了List Comprehensions

import math

xy = [(7, 9), (3, 3), (6, 0), (7, 9)]

distances = [math.sqrt(((xy[i+1][0]-xy[i][0])**2)+((xy[i+1][1]-xy[i][1])**2)) for i in range(len(xy)-1)]

print(distances)

>>> [7.211102550927978, 4.242640687119285, 9.055385138137417]

据我了解,您想求出点 0 和点 1、点 1 和点 2 之间的距离...

如果是,这就是你的答案

i = 0
n = [(7, 9), (3, 3), (6, 0), (7, 9)]
result = []

for item in range(len(n)-1):
   distX = abs(n[i][0] - n[i+1][0])
   distY = abs(n[i][1] - n[i+1][1])

   hypotenuse = math.sqrt((distX*distX) + (distY*distY)) 
   result.append(hypotenuse)

   i =i + 1