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

时间:2022-04-15 07:42:55

I have a list of 2-D points

我有一个二维点列表

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

and a reference point ref = (x0, y0).

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

I now wish to sort the list candidates according to their euclidean distances from the reference point ref, in ascending order.

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

What is the most Pythonic way of doing so?

最恐怖的方式是什么?

3 个解决方案

#1


7  

Euclidean distance between two points (x1, y1) and (x2, y2) is given by:

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

sqrt((x1 - y1)^2 + (x2 - y2)^2))

To sort the list, you can use the formula, and also you can skip the sqrt part, as you are just doing comparison, and not calculating the actual distance. i.e:

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

if x > y then sqrt(x) > sqrt(y)

So, following would work:

所以,以下工作:

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


6  

Write a function to calculate euclidean distance and use that function with the key parameter of the list.sort function.

编写一个函数来计算欧氏距离,并将该函数与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)

#3


2  

The key argument of list.sort() will allow you to pass a function that will be used to derive the sort key of each element.

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

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

#1


7  

Euclidean distance between two points (x1, y1) and (x2, y2) is given by:

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

sqrt((x1 - y1)^2 + (x2 - y2)^2))

To sort the list, you can use the formula, and also you can skip the sqrt part, as you are just doing comparison, and not calculating the actual distance. i.e:

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

if x > y then sqrt(x) > sqrt(y)

So, following would work:

所以,以下工作:

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


6  

Write a function to calculate euclidean distance and use that function with the key parameter of the list.sort function.

编写一个函数来计算欧氏距离,并将该函数与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)

#3


2  

The key argument of list.sort() will allow you to pass a function that will be used to derive the sort key of each element.

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

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