Python3 自定义 sort() 的排序规则

在 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参数? - 知乎

参考:Python3中自定义排序原理 - 知乎

参考:https://blog.csdn.net/chaleaoch_gmail/article/details/102221147

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龚建波

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值