4

2次元点のリストがあります

candidates = [(x1, y1), (x2, y2), (x3, y3), ...]

と基準点ref = (x0, y0)

candidatesここで、基準点からのユークリッド距離に従ってref昇順でリストを並べ替えたいと思います。

そうするための最もPythonicな方法は何ですか?

4

3 に答える 3

10

2 点間のユークリッド距離で(x1, y1)あり、次の(x2, y2)式で与えられます。

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)
于 2013-10-05T13:45:49.970 に答える
8

ユークリッド距離を計算する関数を作成し、その関数を関数の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)
于 2013-10-05T13:39:49.443 に答える