python - 根据对象的属性(即使它们是 NoneType)对 Python 中的对象列表进行排序

标签 python list sorting object

我有包含发票对象的发票列表。 我想根据它们的日期并使用下面的方法对这些对象进行排序。

from operator import attrgetter
invoices_list.sort(key=attrgetter('date'))

这就是我遇到的错误。

TypeError: can't compare FakeDatetime to NoneType

我想根据日期对对象进行升序排列,并且没有日期应该是第一个。然后其他人应该按升序排列。

$ invoices_list[0].date
$ FakeDatetime(2015, 7, 3, 0, 0)

最佳答案

一个简单的 key 包装器就可以完成这项工作:

class DateKey(object):
    def __init__(self, invoice):
        self.value = invoice.date
    def __lt__(self, other):
        if not isinstance(other, (datetime.date, type(None))):
            return NotImplemented
        elif self.value is None:
            return True
        elif other.value is None:
            return False
        else:
            return self.value < other.value

然后使用它:

invoices_list.sort(key=lambda i: DateKey(i))

关于python - 根据对象的属性(即使它们是 NoneType)对 Python 中的对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066669/

相关文章:

python - 如何获取图像的类型(RGB 或 GREY)

python - 如何使用python向MySQL表中添加记录?

java - 迭代数组列表

python - python中的智能排序

sorting - Kubernetes:按年龄升序显示 Pod

python - 闭包:什么是好的用例示例?为什么不是仿函数?它值得负面影响吗?

python - 多行中的 PyYAML 变量

list - 将输入流转换为对象列表

python - 在 Python 中切掉列表中每个(列表)元素中的第一个元素

根据导数或指数级别对 Mathematica 中的公式进行排序