You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用geopy库geodesic计算经纬度距离并存入列表?

解决方法

原代码问题

  • 错误地将整个经纬度列表作为单个坐标点传入geodesic,该方法仅接受单个点的坐标对(如(纬度, 经度)),而非批量列表。
  • 未通过循环遍历所有店铺与顾客的组合,无法生成完整的距离列表。

正确实现代码

先确保安装geopy库:pip install geopy,再运行以下代码:

from geopy.distance import geodesic

# 原始经纬度数据
shop_long = [-123.223, -127.223, -123.223, -123.048]
shop_lat = [49.1534, 55.1303, 49.1534, 53.2563]
cus_long = [-126.07325247944962, -126.07255765553835, -126.07485428820583, 
            -126.0733578858899, -126.07270416708549]
cus_lat = [51.29548801984406, 51.29486187466757, 51.29566033167437, 
           51.295612714656855]

# 将经纬度配对为单个点的坐标(纬度在前,经度在后,符合geopy标准格式)
shops = list(zip(shop_lat, shop_long))
customers = list(zip(cus_lat, cus_long))

distance = []

# 遍历所有店铺,计算每个店铺到所有顾客的距离
for shop in shops:
    shop_cus_dist = []
    for customer in customers:
        # 计算距离,单位为英里(如需公里可替换为.km)
        dist = geodesic(shop, customer).miles
        shop_cus_dist.append(dist)
    distance.append(shop_cus_dist)

# 输出示例:打印每个店铺到顾客的距离
for idx, dists in enumerate(distance):
    print(f"店铺{idx+1}到各顾客的距离(英里):{dists}")

可选调整

如果需要每个顾客到所有店铺的距离,只需调整循环顺序:

distance = []
for customer in customers:
    cus_shop_dist = []
    for shop in shops:
        dist = geodesic(customer, shop).miles
        cus_shop_dist.append(dist)
    distance.append(cus_shop_dist)

关键注意事项

  • 坐标顺序:建议统一使用(纬度, 经度)传入geodesic,避免因顺序错误导致计算偏差。
  • 单位切换:除.miles外,还可使用.km(公里)、.meters(米)等单位获取距离。

内容的提问来源于stack exchange,提问作者Jaspreet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:20:50