Python 计算点之间的距离 - 枚举问题

Python Calculating distances between points - Issues with Enumerate

我有一个坐标列表,我想计算每对坐标之间的距离,例如 A(lon_a, lat_a) 和 B(lon_b;lat_b)。

下面的函数本身运行良好,但我在使用列表理解和枚举函数遍历每个点以获取所有距离的列表时遇到问题。我下面的代码导致了这个错误: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]

您不能只使用枚举来填写列表理解,您可以使用步骤

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)}")

现在使用列表理解格式,您可以获得距离列表(这就是 return 有用的原因)

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