我有一个项目清单X
and Y
坐标。现在,有一种方法需要X
and 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)