2013-10-05 62 views

回答

7

欧氏距离由下式给出:

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) 
2

key参数list.sort()将允许您传递将用于派生每个元素的排序关键字的函数。

candidates.sort(key=lambda x: distance(ref, x)) 
6

写函数来计算欧几里得距离,并使用该函数与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)之间
+1

我会用'math.sqrt(X)'取代'X ** 5',这是约30%的速度。同样,'x * x - 2 * x * xx + xx * xx'比'(x-xx)** 2'更快。 –

+1

@TimPietzcker我同意'math.sqrt(x)'更具可读性,但函数调用总是比** .5更慢。 –

+0

直直而清晰。但是,我想知道是否有可能使其成为单线? –

相关问题