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

后端 未结 3 2029
广开言路
广开言路 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 10:02

    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!

提交回复
热议问题