简介
python 标准模块 functools 中的 cmp_to_key 函数可以将一个 cmp 函数变成一个 key 函数,从而支持自定义排序。
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
它在内部定义了一个类K, 并使用我传入的cmp函数完成了比较关系运算符的重载,
函数返回的是一个类,而参数 key 需要的是一个函数,这里把类当成了函数来用,看起来矛盾,但因为在 Python 中,类和函数都是 callable 的,所以这样做完全可行。
>>> from functools import cmp_to_key
>>> def reverse_cmp(x, y):
... return y - x
...
>>> k_class = cmp_to_key(reverse_cmp)
>>> k1 = k_class(100)
>>> k2 = k_class(200)
>>> k1 < k2
False
# k1 是 self, k2 是 other
以 sorted 函数为例:
传入参数 key 的函数变成了 cmp_to_key 函数的返回值—类 K,在 sorted 内部,类接收一个参数构造一个实例参与比较的是 K 的实例化对象,而 K 已经用自定义的比较函数对比较关系运算符进行了重载,故最终实现了自定义排序。
# 简单使用
>>> a = [1, 2, 5, 3, 9, 4, 6, 8, 7, 0, 12]
>>> def reverse_cmp(x, y):
... return y - x
...
>>> sorted(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12]
>>> sorted(a, key = cmp_to_key(reverse_cmp))
[12, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# 复杂情况
# 可使用 lambda 进一步规定 key 位置
>>> from functools import cmp_to_key
>>> def my_cmp(x, y):
... return x - y
...
>>> L = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
>>> sorted(L, key = cmp_to_key(lambda x, y: my_cmp(x[1], y[1])))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# 或直接在函数中处理
>>> from functools import cmp_to_key
>>> def my_cmp(x, y):
... return x[1] - y[1]
...
>>> L = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
>>> sorted(L, key = cmp_to_key(my_cmp))
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]