问题
I'm trying to write a Python function (without the use of modules) that will iterate through a list of coordinates and find the euclidean distance between two subsequent points (for example, the distance between points a and b, b and c, c and d etc.). After a few hours of searching I came across this post which I thought solved my problem, so I wrote this:
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)
However, this retrieves the distance between the first point and every other point. I've been trying to figure out how to define a variable for the next point in the sequence, but I'm pretty new to Python and just don't quite understand how to get there. I'm currently writing the totalDistance
function like this:
def totalDistance(inputPoints):
dist = []
for item in inputPoints:
pOne = item
pTwo =
coordDist = distance(pOne,pTwo)
dist.append(coordDist)
return sum(dist)
but can't figure out how I would go about defining pTwo.
回答1:
One way of doing this would be:
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)
Basically, record the first item, and iterate from the second item in the list. It's probably better to swap pOne
and pTwo
around for easier understanding, or to be clearer and use more Pythonic names:
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)
回答2:
With a list comprehension and zip this can be done like:
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:]))
Or alternatively for Python 3 (from comments) using map:
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
回答3:
With itertools and 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
来源:https://stackoverflow.com/questions/48980048/pairwise-euclidean-distance-from-a-list-of-points