了解排序函数python的工作原理

时间:2019-01-26 20:58:40

标签: python-3.x sorting

我对python内置排序功能的工作原理有疑问。 我有个人类,它拥有两个属性,例如名称和数字。我想根据名称属性对其进行排序。如果两个名字相等,则应根据数字属性对其进行排序。

def foo(x):
    def bar(y):
        return x + y
    return bar

bar = foo(3)
print(type(bar))    # a function (of one variable with the other fixed to 3)
print(bar(8))       # 11
bar = foo(9)
print(bar(8))       # 17

在这里,我覆盖了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.name, self.number) < (other.name, 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) 函数。但是,仍然不清楚__lt__函数如何使用它。

我认为排序可以在以下代码中进行:

sorted

不过,对我来说,排序函数的工作方式尚不清楚。

0 个答案:

没有答案