Search code examples
pythonlist-comprehensionenumerate

Python Calculating distances between points - Issues with Enumerate


I have got a list of coordinates and I want to calculate the distances between each pair of them, for example the distance between A(lon_a, lat_a) and B(lon_b; lat_b).

The function belows works fine on its own, but I am having problems looping through each point to get a list of all distances using list comprehension and the enumerate function. My code below results in this error: TypeError: float() argument must be a string or a number, not 'enumerate'

from geopy.geocoders import Nominatim
from geopy import distance



 list_coord = ['51.604443', '7.205795', '51.604390', '7.205635', '51.604362', '7.205496', '51.604332', '7.205344', '51.604336', '7.205176', '51.604294', '7.205024', '51.604263', '7.204844', '51.604256', '7.204680', '51.604225', '7.204537', '51.604195', '7.204397', '51.604156', '7.204258', '51.604122', '7.204091', '51.604095', '7.203943', '51.604073', '7.203795', '51.604034', '7.203641', '51.604000', '7.203481', '51.603973', '7.203319', '51.603947', '7.203151', '51.603920', '7.203005', '51.603880', '7.202852', '51.603820', '7.202717', '51.603770', '7.202561', '51.603750', '7.202388', '51.603745', '7.202220', '51.603706', '7.202080']


def calc_dist (lon_a, lat_a, lon_b, lat_b):
    start_coord = (lon_a, lat_a)
    end_coord = (lon_b, lat_b)
    print(distance.distance(start_coord, end_coord).m)


list_dist = [calc_dist ( enumerate(list_coord, 0), enumerate(list_coord, 1), enumerate(list_coord, 2), enumerate(list_coord, 3) )  for i in list_coord]

Solution

  • You can't just fill all in a list comprehension using enumerates, you may use steps

    from itertools import combinations
    
    def calc_dist(lon_a, lat_a, lon_b, lat_b):
        start_coord = (lon_a, lat_a)
        end_coord = (lon_b, lat_b)
        return distance.distance(start_coord, end_coord).m # better use a return, easily to use the method
    
    if __name__ == '__main__':
        locations = list(zip(list_coord[::2], list_coord[1::2])) # associate longitude and latitude to get pairs
        pair_locations = zip(locations, locations[1:])  # make pairs A-B, B-C, C-D, ...
        for pA, pB in pair_locations:                   # get the distance
            print(f"{pA}-{pB} : {calc_dist(*pA, *pB)}")
    

    Now using list comprehension format you can get a list of distances (here's why return is usefull)

    locations = list(zip(list_coord[::2], list_coord[1::2]))
    list_distance = [calc_dist(*pA, *pB) for pA, pB in zip(locations, locations[1:])]