根据指标对候选人列表进行排序 - Python?

Sib*_*ing 3 python sorting list

我有一个二维点列表

candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
Run Code Online (Sandbox Code Playgroud)

和参考点ref = (x0, y0).

我现在希望candidates根据它们与参考点的欧氏距离ref按升序对列表进行排序.

什么是最Python的方式这样做的?

Ash*_*ary 7

编写一个函数来计算欧氏距离,并将该函数与函数的key参数一起使用list.sort.

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)
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我会避免做`sqrt`或'**0.5`.这里不需要. (4认同)
  • 不.`timeit.timeit(setup ="来自math import sqrt",stmt ="[sqrt(x)for x in range(100,200)]")的结果在我的机器上是23秒,而`timeit.timeit(stmt = "[x**.5 for x in range(100,200)]")`需要32秒. (2认同)

Roh*_*ain 7

两点之间的欧氏距离(x1, y1)(x2, y2)由下式给出:

sqrt((x1 - y1)^2 + (x2 - y2)^2))
Run Code Online (Sandbox Code Playgroud)

要对列表进行排序,您可以使用公式,也可以跳过该sqrt部分,因为您只是进行比较,而不是计算实际距离.即:

if x > y then sqrt(x) > sqrt(y)
Run Code Online (Sandbox Code Playgroud)

所以,以下工作:

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)
Run Code Online (Sandbox Code Playgroud)