2次元点のリストがあります
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
と基準点ref = (x0, y0)
。
candidates
ここで、基準点からのユークリッド距離に従ってref
昇順でリストを並べ替えたいと思います。
そうするための最もPythonicな方法は何ですか?
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)
ユークリッド距離を計算する関数を作成し、その関数を関数の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)