sorted复杂排序cmp_to_key

Python3中移除了cmp内建函数,sorted函数也没有了cmp这个关键字参数,但可以通过functools模块中的cmp_to_key来对自定义的cmp函数进行包装,然后就能赋值给sorted函数的关键字参数key,来间接实现Python2中cmp函数用于排序的效果。

cmp_to_key是在python3中使用的,其实就是python2中的cmp函数。

python3不支持比较函数,在一些接受key的函数中(例如sorted,min,max,heapq.nlargest,itertools.groupby),key仅仅支持一个参数,就无法实现两个参数之间的对比,采用cmp_to_key 函数,可以接受两个参数,将两个参数做处理,比如做和做差,转换成一个参数,就可以应用于key关键字之后。

cmp_to_key 返回值小于0,则交换值。如果返回值大于等于0,则不执行任何操作。
注意点:
x = [("a", 1), ("b", 3), ("c", 2)]
在cmp_to_key中,第一个入参是 ("b", 3) ,第二个入参是 ("a", 1)

from functools import cmp_to_key

# 字典按key降序排序,再按val升序排序
a = {"a": 5, "c": 3, "e": 2, "d": 2}


def cmp(val1, val2):
    if val1[0] < val2[0]:
        return 1
    elif val1[0] > val2[0]:
        return -1
    else:
        if val1[1] > val2[1]:
            return 1
        else:
            return -1


sd = sorted(a.items(), key=cmp_to_key(cmp))
print(sd)  # [('e', 2), ('d', 2), ('c', 3), ('a', 5)]


# 我们利用类的 __lt__ 也能实现cmp_to_key
class Info:
    def __init__(self, items):
        self.val = items

    def __lt__(self, other):
        # key 降序
        if self.val[0] < other.val[0]:
            return False
        elif self.val[0] > other.val[0]:
            return True

        # val 升序
        else:
            if self.val[1] > other.val[1]:
                return False
            else:
                return True


b = sorted(a.items(), key=lambda kv: Info(kv))
print(b)  # [('e', 2), ('d', 2), ('c', 3), ('a', 5)]
原文地址:https://www.cnblogs.com/Zzbj/p/15522955.html