总排序不会返回预期输出 python3.x



我有一个包含 6 个人的输入,每个人都持有姓名和号码。我正在尝试编写排序函数以根据它们的数量对它们进行排序。如果两个数字相同,我正在尝试根据名称对它们进行排序。

为了实现它,我使用total_ordering。但是,它不会返回预期的输出。

import numpy as np
from functools import total_ordering

@total_ordering
class Person(object):
    def __init__(self, name, number):
        self.name=name
        self.number=number
    def __repr__(self):
        return "{}, {}".format(self.number, self.name)
    def __lt__(self, other):
        return self.number<other.number
    def __eq__(self, other):
         return (self.number==other.number and self.name==other.name) or self.number==other.number
    def __le__(self, other):
        return (self.number==other.number and self.name<other.name) or self.number<other.number
customList=[
    Person('object', 99),
    Person('michael', 1),
    Person('theodore', 21),
    Person('amazon', 21),
    Person('life', 42),
    Person('tree', 42)
]
a=sorted(customList)
print(a)

代码片段返回[1, michael, 21, theodore, 21, amazon, 42, life, 42, tree, 99, object],但我期望[1, michael, 21, amazon, 21, theodore, 42, life, 42, tree, 99, object]

谢谢。

我会写

def __lt__(self, other):
    return (self.number, self.name) < (other.number, other.name)

同样适用于__eq____le__

最新更新