简体   繁体   English

从元组列表中,获取最接近给定值的元组

[英]from list of tuples, get tuple closest to a given value

Given a list of tuples containing coordinates, I want to find which coordinate is the closest to a coordinate I give in input: 给定一个包含坐标的元组列表,我想找到哪个坐标与我在输入中给出的坐标最接近:

cooList = [(11.6702634, 72.313323), (31.67342698, 78.465323)]
coordinate = (11.6702698, 78.113323)
takenearest(myList, myNumber)
...
(11.6702634, 72.313323)

Please let me know... 请告诉我...

For your data 为您的数据

cooList = [(11.6702634, 72.313323), (31.67342698, 78.465323)]
coordinate = (11.6702698, 78.113323)

the shortest Pythonic answer is: 最短的Python答案是:

nearest = min(cooList, key=lambda x: distance(x, coordinate))

with a function distance(a, b) returning the distance between the points a and b as a float, which you have to define yourself. 函数distance(a, b)以浮点数形式返回点ab之间的距离,您必须定义自己。

Now you have to decide how you calculate the distance: using simple a² + b² = c² , some geographical formula or a dedicated library. 现在,您必须决定如何计算距离:使用简单的a² + b² = c² ,某些地理公式或专用的库。

If I understand you right, you want the coordinate from the list that has the least distance to the given coordinate. 如果我理解正确,那么您需要列表中与给定坐标距离最小的坐标。 That means you can just loop through the list like that: 这意味着您可以像这样遍历列表:

def closest_coord(list, coord):
    closest = list[0]
    for c in list:
        if distance(c, coord) < distance(closest, coord):
            closest = c
    return closest

To calculate the distance between two variables, just use Pythagoras. 要计算两个变量之间的距离,只需使用毕达哥拉斯即可。

def distance(co1, co2):
    return sqrt(pow(abs(co1[0] - co2[0]), 2) + pow(abs(co1[1] - co2[2]), 2))

I hope this helps! 我希望这有帮助!

>>> min(cooList, key=lambda c: (c[0]- coordinate[0])**2 + (c[1]-coordinate[1])**2)
(11.6702634, 72.313323)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM