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

如何计算两组坐标列表间的欧氏距离(Euclidean distance)矩阵

实现方案

这里提供两种常用的实现思路,可根据数据规模自由选择:

1. 纯Python原生实现(无额外依赖,适合小规模数据)

直接用嵌套列表推导式遍历两个坐标列表即可生成距离矩阵,矩阵行对应仓库索引、列对应门店索引,dist_matrix[i][j]就是第i个仓库到第j个门店的距离。

wh_coords=[(134,104),(141,82),(128,29),(120,49),(56,104),(14,60),(16,51),(17,94),(50,102),(44,99)]
st_coords=[(53,138),(79,130),(72,76),(53,3),(85,111),(102,39),(122,18),(147,7),(40,150),(46,19),(57,19),(88,113)]

import math
def calc_euc_dist(point_1, point_2): 
   distance = math.sqrt((point_1[0] - point_2[0])**2 + (point_1[1] - point_2[1])**2)
   return distance

# 生成距离矩阵
dist_matrix = [
    [calc_euc_dist(wh, st) for st in st_coords]
    for wh in wh_coords
]

# 示例输出:第一个仓库到第一个门店的距离
print(dist_matrix[0][0])

如果需要保留配对标识,也可以生成字典格式的结果:

dist_pairs = {
    f"仓库{i}-门店{j}": calc_euc_dist(wh, st)
    for i, wh in enumerate(wh_coords)
    for j, st in enumerate(st_coords)
}

2. NumPy实现(计算效率高,适合大规模数据)

如果仓库、门店数量达到数千甚至更高,用NumPy的广播机制计算速度远快于原生循环:

import numpy as np

# 坐标转换为NumPy数组
wh_arr = np.array(wh_coords)
st_arr = np.array(st_coords)

# 一步计算所有配对距离生成矩阵
dist_matrix = np.sqrt(np.sum((wh_arr[:, np.newaxis] - st_arr)**2, axis=2))

# 输出结果和原生计算完全一致
print(dist_matrix[0, 0])

注意事项

你提到坐标为经纬度,这里额外提醒:如果是真实地球经纬度,当前的欧氏距离计算的是平面投影距离,不是实际地表里程,如果需要真实通行距离,需要替换为哈弗辛(Haversine)公式计算球面距离。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:15:03