我通常了解如何使用lambda
函数或其他数组作为键对数组进行排序,但很难理解自定义类作为函数中键sorted()
以下用法。您能解释一下它是如何工作的,以及为什么打印出的第一个数字在输出中是 5?
class STR(str):
def __lt__(self, other):
print(self, other)
return self + other < other + self
list_ = ['3', '30', '34', '5', '9']
sorted(list_, key=STR, reverse=True)
output:
5 9
34 5
30 34
3 30
3 5
3 34
3 30
['9', '5', '34', '3', '30']
但是,以下代码不能很好地工作。输出错误。这是否意味着默认情况下排序使用__lt__
而不是__gt__
方法? 从输出来看,__gt__
从未被调用过,否则它应该打印出来(自身,其他)。
class STR(str):
def __gt__(self, other):
print(self, other)
return self + other > other + self
list_ = ['3', '30', '34', '5', '9']
sorted(list_, key=STR, reverse=True)
output:
['9', '5', '34', '30', '3']
在这种情况下,您的自定义类继承自str
并重载它__lt__
方法。 使用 less than 运算符时调用__lt__()
。当您将此自定义类作为键传递时sorted()
,它首先将您的类映射到列表中的项,然后使用<
进行比较,这将调用自定义类中的重载__lt__()
方法。至于为什么首先比较'5'
,那是因为你指定了reverse=True
所以它从列表的末尾开始向后比较。