通过循环查找最接近的坐标(Python)

时间:2017-09-04 22:29:43

标签: python-3.x loops dictionary for-loop distance

x = {'d': (4, 2), 'b': (4, 4), 'c':  (2, 2), 'a': (4, 0)}

如何使用欧几里德距离并假设列表从d开始,从词典中获取基于从一个坐标到下一个坐标的最近距离排序的键列表?

列表应如下所示:['d', 'a', 'c', 'b']

原因是坐标a与坐标d的距离最短,坐标a将成为第二个参考点,与包含坐标的字典中的其余坐标进行比较{ {1}}和c。然后发现坐标b是最接近坐标c的坐标。这个过程一直持续到字典中没有更多的参考点。

2 个答案:

答案 0 :(得分:0)

字典是常量。传递路径['d']并保留设置(['a','b','c'])到find_closest功能。它查看path[-1]与剩余集合中每个点之间的距离,将获胜者从集合移动到列表末尾。循环直到该集为空。

答案 1 :(得分:0)

  

坐标a与坐标d的距离最短,

不,看看你的示例坐标,a,b& c与d等距离,即2,因此有多种有效的解决方案:

from math import sqrt

def distance(p):
    p1, p2 = points[p]
    q1, q2 = points[path[-1]]

    return sqrt((q1 - p1) ** 2 + (q2 - p2) ** 2)

points = {'d': (4, 2), 'b': (4, 4), 'c':  (2, 2), 'a': (4, 0)}

path = ['d']  #  assuming the list starts from d

while len(path) < len(points):
    path.append(sorted([point for point in points if point not in path], key=distance)[0])

print(path)

<强>输出

> python3 test.py
['d', 'b', 'c', 'a']
>
相关问题