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

你离开我真会死。 提交于 2019-12-04 02:03:53

问题


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...


回答1:


For your data

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

the shortest Pythonic answer is:

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.

Now you have to decide how you calculate the distance: using simple a² + b² = c², some geographical formula or a dedicated library.




回答2:


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!




回答3:


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


来源:https://stackoverflow.com/questions/28339199/from-list-of-tuples-get-tuple-closest-to-a-given-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!