Skip to main content
 首页 » 编程设计

python之如何按到给定点的距离对点列表进行排序

2025年05月04日44mq0036

我有一个具有 X 和 Y 坐标的项目列表。现在,有一种方法采用 X 和 Y 参数,并应返回根据给定参数从最近到最远排序的坐标列表。

基本上,它看起来像这样:

class Point: 
    x = 0.0 
    y = 0.0 
 
# List of points 
points = ... 
 
def get_ordered_list(x, y): 
    # return 'points' ordered by distance to (x,y) 

我是 Python 的新手,所以我几乎不知道如何订购这些元素。我该怎么做?

请您参考如下方法:

您可以传递自定义函数以使用 key 参数进行排序,例如使用欧几里得范数排序,如下所示:

def get_ordered_list(points, x, y): 
   points.sort(key = lambda p: (p.x - x)**2 + (p.y - y)**2) 
   return points