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

如何从Python字典中找出指定坐标的3个最近城市

获取指定坐标最近的3个城市的方法

嘿,这个问题其实很好解决,核心思路就是计算每个城市与目标坐标的距离,然后按距离排序取前3位。下面我给你两种实现方案,分别对应快速近似和准确的实际地表距离:

方法一:快速近似(欧几里得距离)

如果你的城市都在较小的地理范围内,用欧几里得距离计算足够快速且差异不大。直接用坐标的平方差开根号就能得到近似距离:

import math

# 目标坐标
target_coords = (52.2319581, 21.0067249)
# 城市坐标字典
cities = {
    'Brwinów': (52.133333, 20.716667),
    'Warszawa Bielany': (52.283333, 20.966667),
    'Legionowo': (52.4, 20.966667),
    'Warszawa-Okęcie': (52.16039, 20.961674),
    'Warszawa': (52.280957, 20.961348),
    'Belsk Duży': (51.833333, 20.8)
}

# 计算每个城市的距离,存储为(距离,城市名)的元组
city_distances = []
for city_name, coords in cities.items():
    # 欧几里得距离公式
    distance = math.sqrt((coords[0] - target_coords[0])**2 + (coords[1] - target_coords[1])**2)
    city_distances.append((distance, city_name))

# 按距离从小到大排序
city_distances.sort()

# 取最近的3个城市
top_3_cities = city_distances[:3]

# 输出结果
print("最近的3个城市(欧几里得近似距离):")
for dist, name in top_3_cities:
    print(f"- {name}: {dist:.4f} 坐标单位")

运行后会得到类似这样的结果:

最近的3个城市(欧几里得近似距离):
- Warszawa Bielany: 0.0651 坐标单位
- Warszawa: 0.0668 坐标单位
- Warszawa-Okęcie: 0.0846 坐标单位

方法二:准确计算(球面距离,Haversine公式)

如果需要准确的实际地表距离(单位:公里),推荐用Haversine公式,它专门用于计算球面上两点的最短距离:

import math

def haversine_distance(coord1, coord2):
    """计算两个经纬度坐标之间的球面距离(公里)"""
    # 将度数转换为弧度
    lat1, lon1 = math.radians(coord1[0]), math.radians(coord1[1])
    lat2, lon2 = math.radians(coord2[0]), math.radians(coord2[1])
    
    # Haversine公式核心计算
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    
    # 地球平均半径(公里)
    earth_radius = 6371
    return earth_radius * c

# 目标坐标和城市字典(和上面一致)
target_coords = (52.2319581, 21.0067249)
cities = {
    'Brwinów': (52.133333, 20.716667),
    'Warszawa Bielany': (52.283333, 20.966667),
    'Legionowo': (52.4, 20.966667),
    'Warszawa-Okęcie': (52.16039, 20.961674),
    'Warszawa': (52.280957, 20.961348),
    'Belsk Duży': (51.833333, 20.8)
}

# 计算距离并排序
city_distances = []
for city_name, coords in cities.items():
    distance = haversine_distance(target_coords, coords)
    city_distances.append((distance, city_name))

city_distances.sort()
top_3_cities = city_distances[:3]

# 输出结果
print("最近的3个城市(实际地表距离):")
for dist, name in top_3_cities:
    print(f"- {name}: {dist:.2f} km")

运行后的结果会是实际的公里数,比如:

最近的3个城市(实际地表距离):
- Warszawa: 6.26 km
- Warszawa Bielany: 6.33 km
- Warszawa-Okęcie: 8.37 km

两种方案都能满足需求,你可以根据自己的场景选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:27:43