从点列表中成对欧几里德距离
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从点列表中成对欧几里德距离相关的知识,希望对你有一定的参考价值。
我正在尝试编写一个Python函数(不使用模块),它将迭代坐标列表并找到两个后续点之间的欧氏距离(例如,点a和b,b和c之间的距离,c和d等)。经过几个小时的搜索,我遇到了this post,我认为这解决了我的问题,所以我写了这个:
myList = [[2, 3], [3,4], [4,5], [5,6], [6,7]]
def distance(pointOne,pointTwo):
eucDist = ((pointOne[0] - pointTwo[0])**2 + (pointOne[1] - pointTwo[1])**2)**0.5
return eucDist
def totalDistance(inputPoints):
dist = []
for item in inputPoints[1:]:
coordDist = distance(inputPoints[0],item)
dist.append(coordDist)
return sum(dist)
print totalDistance(myList)
但是,这将检索第一个点和每个其他点之间的距离。我一直在试图弄清楚如何为序列中的下一个点定义一个变量,但我对Python很新,只是不太明白如何到达那里。我正在编写像这样的totalDistance
函数:
def totalDistance(inputPoints):
dist = []
for item in inputPoints:
pOne = item
pTwo =
coordDist = distance(pOne,pTwo)
dist.append(coordDist)
return sum(dist)
但无法弄清楚我将如何定义pTwo。
答案
这样做的一种方法是:
def totalDistance(inputPoints):
dist = []
pTwo = inputPoints[0]
for item in inputPoints[1:]:
pOne = pTwo
pTwo = item
coordDist = distance(pOne,pTwo)
dist.append(coordDist)
return sum(dist)
基本上,记录第一个项目,并从列表中的第二个项目迭代。最好交换pOne
和pTwo
以便更容易理解,或者更清楚并使用更多的Pythonic名称:
def totalDistance(input_points):
dist = []
this_item = input_points[0]
for item in input_points[1:]:
prev_item = this_item
this_item = item
coord_dist = distance(prev_item, this_item)
dist.append(coord_dist)
return sum(dist)
另一答案
使用list comprehension和zip可以这样做:
Code:
def distance(point_one, point_two):
return ((point_one[0] - point_two[0]) ** 2 +
(point_one[1] - point_two[1]) ** 2) ** 0.5
def total_distance(points):
return sum(distance(p1, p2) for p1, p2 in zip(points, points[1:]))
或者对于使用map
的Python 3(来自评论):
def total_distance(points):
return sum(map(distance, points, points[1:]))
Test Code
my_points = [[2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
print(total_distance(my_points))
Results:
5.656854249492381
另一答案
使用itertools和NumPy:
from itertools import tee
import numpy as np
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def total_dist(points):
return np.sum(np.sqrt(np.sum(np.square(
np.diff(tuple(pairwise(points)))), axis=-2)))
total_dist(myList)
# 5.656854249492381
以上是关于从点列表中成对欧几里德距离的主要内容,如果未能解决你的问题,请参考以下文章