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的方式这样做的?
编写一个函数来计算欧氏距离,并将该函数与函数的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)
两点之间的欧氏距离(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)
归档时间: |
|
查看次数: |
1318 次 |
最近记录: |