在 Python2 中,sort 和 sorted 可以通过关键字参数 cmp 指定排序规则,但在 Python3 中这个参数给去掉了:
Python2: list.sort(cmp=None, key=None, reverse=False)
Python3: list.sort(key=None, reverse=False)
(其中,参数 key 指定带有一个参数的函数,用于从每个列表元素中提取比较键;参数 reverse 可以指定为逆向排序。)
根据 Python3 的文档:https://docs.python.org/zh-cn/3/library/stdtypes.html?highlight=sort#list.sort
可以使用 functools.cmp_to_key() 将 Python2 风格的 cmp 函数转换为 key 函数。
import functools
strs=[3,4,1,2]
#自定义排序规则
def my_compare(x,y):
if x>y:
return 1
elif x<y:
return -1
return 0
#分别使用sorted和list.sort
print(strs)
print(sorted(strs,key=functools.cmp_to_key(my_compare)))
print(strs)
strs.sort(key=functools.cmp_to_key(my_compare))
print(strs)
Python3.10 输出结果:
上面一个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
这段代码很巧妙,在函数内部创建了一个class,并且返回了这个class,在这个class中调用了传入的cmp函数进行了运算符重载。这样使得两个class的对象就可以进行比较了。
知乎讨论:python3 为什么取消了sort方法中的cmp参数? - 知乎
参考:https://blog.csdn.net/chaleaoch_gmail/article/details/102221147