Skip to main content
 首页 » 编程设计

python之如何从左上角到右下角排列坐标

2025年05月04日20qq78292959

我有一个类对象列表 my_rectangle:

class my_rectangle: 
    def __init__(self,text,x_start,y_start,x_end,y_end): 
        self.text=text 
        self.x_start=x_start 
        self.y_start=y_start 
        self.x_end=x_end 
        self.y_end=y_end 
        self.x_centroid=(self.x_start+self.x_end)/2 
        self.y_centroid=(self.y_start+self.y_end)/2 

使用给出质心坐标的类属性(x_centroid 和 y_centroid),我想对这个列表进行排序,使用从左到右的顺序然后从上到下(正常的英文阅读顺序)?

假设我有:

A=my_rectangle('Hi,',1,3,2,4) 
B=my_rectangle('Im',3,3,3,4) 
C=my_rectangle('New',1,1,2,2) 
my_list=[C,B,A] 

我想订购它以获得:

my_sorted_list=[A,B,C] 

这是文本的表示:

""" Hi, I'm 
    New  
""" 

请您参考如下方法:

生成排序列表是内置函数的专长 sorted() .

使用多个值进行排序可以通过提供一个 key 函数来完成,该 key 函数将值作为元组返回。然后根据元组的字典顺序对结果列表进行排序。

#UNTESTED 
my_sorted_list = sorted(my_list, key=lambda item: (item.x_centroid, item.y_centroid))