Distance formula between two points in a list

前端 未结 7 1730
刺人心
刺人心 2021-01-31 19:39

I need to take a list I have created and find the closest two points and print them out. How can I go about comparing each point in the list?

There isn\'t any need to pl

7条回答
  •  盖世英雄少女心
    2021-01-31 19:51

    It is more convenient to rewrite your distance() function to take two (x, y) tuples as parameters:

    def distance(p0, p1):
        return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
    

    Now you want to iterate over all pairs of points from your list fList. The function iterools.combinations() is handy for this purpose:

    min_distance = distance(fList[0], fList[1])
    for p0, p1 in itertools.combinations(fList, 2):
        min_distance = min(min_distance, distance(p0, p1))
    

    An alternative is to define distance() to accept the pair of points in a single parameter

    def distance(points):
        p0, p1 = points
        return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
    

    and use the key parameter to the built-in min() function:

    min_pair = min(itertools.combinations(fList, 2), key=distance)
    min_distance = distance(min_pair)
    

提交回复
热议问题