从元组列表中找到最接近的元组-Python
我有包含纬度和经度的元组列表
list_of_tuples = [
(48.383015375128444, 11.112193974456085),
(48.38301264157321, 11.112228110565772),
(48.383007738644274, 11.112256631732311),
(48.38300037666574, 11.112279943681244),
(48.382990265960615, 11.11229845213883),
(48.38297711685105, 11.112312562832122),
(48.382960639658386, 11.112322681489001),
(48.38294054470342, 11.112329213838153),
(48.38291654230646, 11.112332565609025)
]
现在我有另一个坐标:
coordinate = 48.36720362305641, 11.112587917596102
我想知道哪个是上面列表中最接近给定的元组 coordinate
我试过:
min(list_of_tuples, key=lambda c: (point[0]- coordinate[0])**2 + (point[1]-coordinate[1])**2)
使用上面的代码时,我总是从列表中获得第一个元组。
回答
您没有在 lambda 函数中使用局部变量,而是引用了point在其他地方定义的名为的变量。
min(list_of_tuples, key=lambda point: (point[0] - coordinate[0])**2 + (point[1] - coordinate[1])**2)
我重命名c为point,因此您的功能仍然有效并且很冗长。