因此,为列表中的每个项调用键函数
. 但是当你使用
cmp_to_key
source code, it is equivalent to
:
def cmp_to_key(mycmp):
"""Convert a cmp= function into a key= function"""
class K(object):
__slots__ = ['obj']
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
__hash__ = None
return K
事实上
如果需要,可以用C实现
see that implementation
,但实际上是一样的)
比较函数
调用次数与比较发生的次数相同(另一方面,排序算法仅使用
<
项目之间的比较,但您可能会使用
对于其他需要完全丰富的比较实现的事情)。CPython使用Timsort,这是一种高度调优的自适应合并排序,它具有最坏情况下的O(N*log N)行为(但对于几乎排序的数据,最佳情况下可以是O(N))