Reputation: 85
Within a list, there are coordinates with x and y values.
[(7, 9), (3, 3), (6, 0), (7, 9)]
I can calculate the distance between two points.
distance_formula = math.sqrt(((x[j]-x[i])**2)+((y[j]-y[i])**2))
I am having a hard time going through the list and calculating the distance between each point. I want to calculate the distance between the first index and second index, second index and third index, third index and forth index...
Upvotes: 2
Views: 1992
Reputation: 82
As I understood you want to find the distances between point 0 and point 1, point 1, and point 2...
if so here is your answer
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
Upvotes: 0
Reputation: 62403
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]
Upvotes: 1
Reputation: 2533
You can do that with zip()
. zip()
will make pairs of coordinates and let you iterate through them conveniently.
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)
Upvotes: 2