在Python中,根据对象的属性(即使它们不是类型)对对象列表进行排序

2024-10-03 06:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有发票清单,其中包括发票对象。 我想根据它们的日期和用途来订购这些物品。你知道吗

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)

Tags: 对象keyfromimportdate发票sort物品
3条回答

一个简单的密钥包装器将完成这项工作:

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))

编写一个自定义比较函数,该函数知道如何比较FakeDateTimeNone对象,然后通过指定cmp关键字参数来告诉sort()使用此函数。你知道吗

如果您为None设置了一些默认值(比如0),您可以执行以下操作:

invoices_list.sort(key=lambda invoice: invoice.get('date') if (invoice != None) else 0)

相关问题 更多 >