【发布时间】:2017-02-18 00:23:49
【问题描述】:
我希望能够按一个属性对类列表进行排序,该属性恰好是另一个类 Date。我做了一些研究,想使用sorted(list, key=lambda x:date) 排序方法,但是看到日期本身就是一个类,我如何在日期中编写__lt__ 函数以允许我按时间顺序排序?
我想要一些类似的东西:
if self.year!= other.year:
return self.year < other.year
elif self.month != pther.month
...
等等。
这是我的 Date 类:
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
我应该提一下,这是我第一次使用 Python,所以我不太擅长。
提前致谢!
【问题讨论】:
-
你的意思是对象列表吗?
-
只是好奇:为什么要这样存储日期而不是使用内置日期?
-
@Sebastian Wozny 抱歉,是的,我指的是对象
-
如果你真的想要这样的东西,我认为你走在了一个很好的轨道上。为什么不写呢?
-
@SebastianWozny 我在语法上遇到了更多问题。您是否继续将我在那里的内容写入
__lt__函数?当我调用 sorted 时会对其进行排序?