Python 如何按到给定点的距离排列点列表?

Python 如何按到给定点的距离排列点列表?,python,Python,我有一个带有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) def get_ordered_list(points, x

我有一个带有
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)
def get_ordered_list(points, x, y):
   points.sort(key = lambda p: (p.x - x)**2 + (p.y - y)**2)
   return points
def get_ordered_list(x, y):
    target_point = Point(x, y)
    points.sort(key=lambda p: distance(p, target_point))

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

你需要一个函数来计算两点之间的距离,我把这个函数留给你。它将返回两个点之间的距离,一个点是您的主要点,另一个是列表中的点


在点数组的
排序方法中使用此函数。

您可以通过自定义函数使用
参数进行排序,例如使用欧几里德范数进行排序,如下所示:

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)
def get_ordered_list(points, x, y):
   points.sort(key = lambda p: (p.x - x)**2 + (p.y - y)**2)
   return points
def get_ordered_list(x, y):
    target_point = Point(x, y)
    points.sort(key=lambda p: distance(p, target_point))
请参阅list的方法,尤其是键参数。它允许您放置一个函数,该函数返回用于排序的键。因此,在您的示例中,可能是这样的:

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)
def get_ordered_list(points, x, y):
   points.sort(key = lambda p: (p.x - x)**2 + (p.y - y)**2)
   return points
def get_ordered_list(x, y):
    target_point = Point(x, y)
    points.sort(key=lambda p: distance(p, target_point))
假设
distance(a,b)
返回点
a
b
之间的距离。还要注意的是,
sort()
对列表进行适当排序,即修改原始列表。如果要返回已排序的新列表,请使用函数

顺便说一句,
x
y
字段是类字段,您定义的类可能无法按预期工作。要使它们成为实例字段,您必须在构造函数中定义它们:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

您可以在排序函数中使用键

class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

 def distance(p1, p2):
     return ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5

 sorted_points = sorted(points, key=lambda e: distance(e, target))

您需要将
作为您的function@maxymoo这不是我的代码的完整示例,只是“类似这样的东西”的示例。谢谢!尽管如此,我只对顺序感兴趣,而不是确切的距离,因此比较时不需要平方根。:)@你知道这个方法的时间复杂度是多少吗?i、 e.实现类似quickselect的东西会更有效吗?@ColinRicardo python使用,不确定quickselect是什么