用于比较的自定义 __lt__ 方法

Pre*_*ach 4 python sorting list

我希望能够按一个属性对类列表进行排序,这恰好是另一个类 Date。我做了一些研究,想使用sorted(list, key=lambda x:date)排序方法,但是看到日期本身就是一个类,我如何__lt__在日期中编写一个函数来让我按时间顺序排序?

我想要一些类似的东西:

if self.year!= other.year:
    return self.year < other.year
elif self.month != pther.month
...
Run Code Online (Sandbox Code Playgroud)

等等。

这是我的日期课程:

class Date:
    def __init__(self, month, day, year, minute, hour, string):
        self.month = month
        self.day = day
        self.year = year
        self.minute = minute
        self.hour = hour
        self.string = string
Run Code Online (Sandbox Code Playgroud)

我应该提一下,这是我第一次使用 Python,所以我不太擅长这个。

提前致谢!

Rob*_*obᵩ 5

比较两个复杂数据结构的简单方法是按正确的排序顺序比较它们的属性元组。尝试这个:

class Date:
    def __init__(self, month, day, year, minute, hour, string):
        self.month = month
        self.day = day
        self.year = year
        self.minute = minute
        self.hour = hour
        self.string = string
    def __lt__(self, other):
        return (self.year, self.month, self.day, self.hour, self.minute) < \
               (other.year, other.month, other.day, other.hour, other.minute)

assert Date(4, 15, 2016, 30, 12, '') < \
       Date(4, 16, 2016, 0, 0, '') < \
       Date (1, 1, 2017, 59, 23, '')

assert not (Date(4, 16, 2016, 0, 0, '') < Date(4, 15, 2016, 30, 12, ''))
Run Code Online (Sandbox Code Playgroud)

当然,这只实现了<. 根据您的代码的性质,您可能希望实现所有其他比较函数>==!=、 等。一种方便的方法是使用@functools.total_ordering类装饰器。

参考: