标题使用functools模块中的cmp_to_key函数自定义排序
import functools
def cmp(a, b):
if b < a:
return -1
if a < b:
return 1
return 0
a = [1, 2, 5, 4]
print(sorted(a, key=functools.cmp_to_key(cmp)))
# [5, 4, 2, 1]
# 上面这个方法实现了降序排列,因为 -1 代表我们逻辑上认为 a<b , 而实际上 b<a
cmp_to_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.