我具有2-d点根据度量对候选列表进行排序 - Python?
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
列表和参考点ref = (x0, y0)
。
我现在想根据它们与参考点ref
的欧氏距离按升序对candidates
列表进行排序。
什么是最Python的方法这样做?
我具有2-d点根据度量对候选列表进行排序 - Python?
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
列表和参考点ref = (x0, y0)
。
我现在想根据它们与参考点ref
的欧氏距离按升序对candidates
列表进行排序。
什么是最Python的方法这样做?
欧氏距离由下式给出:
sqrt((x1 - y1)^2 + (x2 - y2)^2))
排序列表中,您可以用公式,也可以跳过sqrt
部分,因为你只是做比较,而不是计算实际距离。即:
if x > y then sqrt(x) > sqrt(y)
因此,以下将工作:
ref = (x0, y0)
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
candidates.sort(key=lambda x: (x[0] - ref[0]) ** 2 + (x[1] - ref[1]) ** 2)
key
参数list.sort()
将允许您传递将用于派生每个元素的排序关键字的函数。
candidates.sort(key=lambda x: distance(ref, x))
写函数来计算欧几里得距离,并使用该函数与list.sort
函数的key
参数。
ref = (x0, y0)
def euclidean(coords):
xx, yy = ref
x, y = coords
return ((x-xx)**2 + (y-yy)**2)**0.5
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
candidates.sort(key=euclidean)
两点
(x1, y1)
和
(x2, y2)
之间
我会用'math.sqrt(X)'取代'X ** 5',这是约30%的速度。同样,'x * x - 2 * x * xx + xx * xx'比'(x-xx)** 2'更快。 –
@TimPietzcker我同意'math.sqrt(x)'更具可读性,但函数调用总是比** .5更慢。 –
直直而清晰。但是,我想知道是否有可能使其成为单线? –