簡體   English   中英

如何從左上方到右下方訂購坐標?

[英]How to order coordinates from top left to bottom right?

我有一個類對象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_centroidy_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函數可以完成使用多個值的排序,該鍵函數將值作為元組返回。 然后根據元組的字典順序對結果列表進行排序。

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

您可以通過定義__lt__方法使自定義類可排序。 這照顧了默認排序中使用的<運算符。

class 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

    @property
    def centroid(self):
        return (self.x_start+self.x_end)/2, (self.y_start+self.y_end)/2

    def __lt__(self, other):
        """Using "reading order" in a coordinate system where 0,0 is bottom left"""
        try:
            x0, y0 = self.centroid
            x1, y1 = other.centroid
            return (-y0, x0) < (-y1, x1)
        except AttributeError:
            return NotImplemented

    def __repr__(self):
        return 'Rectangle: ' + self.text

我將centroid定義為屬性,以便在初始化Rectangle后更改其他坐標時它將更新。

如果使用問題中的數據,則將獲得此輸出。

>>> rectangles = [
...     Rectangle('A',1,3,2,4),
...     Rectangle('B',3,3,3,4),
...     Rectangle('C',1,1,2,2), 
... ]
>>> print(sorted(rectangles))
[Rectangle: A, Rectangle: B, Rectangle: C]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM