以下是一个示例代码,展示了如何保持坐标排序:
# 定义一个坐标类
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
# 定义 __lt__ 方法,用于排序
def __lt__(self, other):
if self.x == other.x:
return self.y < other.y
return self.x < other.x
# 创建一些坐标对象
coordinates = [Coordinate(1, 3), Coordinate(2, 2), Coordinate(1, 2), Coordinate(2, 1)]
# 使用 sort() 方法进行排序,会自动调用 __lt__ 方法进行比较
coordinates.sort()
# 打印排序后的坐标
for coordinate in coordinates:
print(f'({coordinate.x}, {coordinate.y})')
运行以上代码,输出结果为:
(1, 2)
(1, 3)
(2, 1)
(2, 2)
可以看到,坐标对象按照 x 坐标进行排序,如果 x 坐标相同,则按照 y 坐标进行排序。