Python中对象的排序方式

2024-03-29 13:50:09 发布

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

假设我有一些对象的列表lst。在

如果没有提供键函数,使用什么值来执行sorted(lst)?是杂凑还是身份证?在


Tags: 对象函数列表sorted身份证lst
2条回答

Pythonsort()

This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

参考:list.sort()

如果没有提供密钥,sort只使用<运算符,如本例所示:

class A:
    def __init__(self,a):
        self.a = a
    def __lt__(self,other):
        return self.a < other.a

    def __repr__(self):
        return str(self.a)

lst = [A(12),A(10),A(44)]
print(sorted(lst))

我得到了:

^{pr2}$

sort在内部仅使用定义的__lt__(小于)运算符,不等于不高于。仅使用<运算符执行排序。在

(注释__lt__运算符会导致TypeError: unorderable types: A() < A()

相关问题 更多 >