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

如何计算Python字典中不同客户多坐标间的所有欧氏距离

解决不同客户所有坐标组合的欧氏距离计算问题

步骤1:实现欧氏距离函数

先补全欧氏距离的计算逻辑,原代码中用到的euclidean_distance未给出具体实现:

import math

def euclidean_distance(coord1, coord2):
    return math.sqrt((coord1[0] - coord2[0])**2 + (coord1[1] - coord2[1])**2)

步骤2:遍历所有坐标组合计算距离

原代码仅计算了每个客户的第一个坐标之间的距离,要覆盖所有组合,需要在客户对循环的基础上,嵌套两层循环遍历每个客户的两个坐标:

locations = {
    1: [(17.186463384962565, -112.35762426972929), (-17.362219355529177, 140.79092146084173)],
    2: [(5.740268073287439, -83.6299751315692), (-51.314275844432835, 165.06524262125532)],
    3: [(1.7593699294955343, 136.62055358721852), (24.298602662279094, -156.1279333844176)],
    4: [(34.38895496244045, -110.77238417799168), (-76.86962027927443, -169.7646833442151)]
}

distance = {}

# 遍历所有不同客户对
for i in locations:
    for j in locations:
        if i != j:
            # 遍历客户i的两个坐标(序号从1开始)
            for i_coord_idx, coord_i in enumerate(locations[i], start=1):
                # 遍历客户j的两个坐标(序号从1开始)
                for j_coord_idx, coord_j in enumerate(locations[j], start=1):
                    # 用元组作为键,明确标识坐标组合
                    key = (i, i_coord_idx, j, j_coord_idx)
                    distance[key] = euclidean_distance(coord_i, coord_j)

# 可选:打印结果,保留4位小数
for pair, dist in distance.items():
    print(f"{pair}: {dist:.4f}")

说明

  • 最终的distance字典中,每个键是(客户编号, 该客户坐标序号, 另一客户编号, 另一客户坐标序号)的元组,对应的值是这两个坐标的欧氏距离,确保所有组合都被覆盖且无重复键。
  • 如果需要更易读的键名,也可以将键改为类似('客户1_坐标1', '客户2_坐标2')的字符串格式。

内容的提问来源于stack exchange,提问作者Javier Isaac Torres Vergara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:45:12