Search code examples
pythonloopscoordinatespython-itertoolshaversine

Iterating over pairs of coordinates in Python


I have a list of coordinates:

[(52.472665, -1.8977818),
(52.47455886, -1.90080653),
(52.4515712, -1.9327772),
(52.45028622, -1.93212766),..]

I am trying to write code that will allow me to calculate the distance between each one using the Haversine module:

(pseudo code)

for points in daycoords1:

p1 = day1coords[0]

p2 = day1coords[1]

dist_miles = haversine(p1, p2, miles=True)

distday1.append(dist_miles)

Is there a way to pull in coordinates one and two, measure the distance, two and three and mesaure that distance etc.

I have been trying to use itertools and zip() but I am yet to have any luck.


Solution

  • I'm not exactly sure what function you want to use from the haversine module, but to compare two consecutive items in your list of coordinates you can use a list comprehension with a zip of slices of your coordinates:

    coords = [(52.472665, -1.8977818),
    (52.47455886, -1.90080653),
    (52.4515712, -1.9327772),
    (52.45028622, -1.93212766)]
    
    distances = [haversine(p1, p2, miles=True) for p1, p2 in zip(coords[:-1], coords[1:])]
    

    This will compare p1 to p2, p2 to p3, p3 to p4 and so on....