对于预期的输出python3.x,总订购不返回

时间:2019-01-25 17:22:50

标签: python-3.x sorting

我有一个包含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]

谢谢。

1 个答案:

答案 0 :(得分:1)

我会写

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

类似于__eq____le__