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

后端 未结 3 2058
广开言路
广开言路 2021-01-07 09:40

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


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-07 09:57

    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.

提交回复
热议问题