python3 sorted() 自定义比较函数

def custom_sort(preprocess_func=lambda x: x):
    """
    自定义排序方法
    :param preprocess_func: 预处理函数,用于排序对象是元素内部的某一个元素时处理
    比如:排序对象为 : ['('a', 3), ('b', 2)] 时 preproess_func = lambda x: x[1]
    排序对象为:[2, 1, 3] 时: preprocess_func = lambda x: x 即默认,可不传
    :return: 排序函数
    """
    def sort_function(x, y):
        """
        根据 preprocess_func 定制的排序函数
        :param x:
        :param y:
        :return: x > y: 1, x < y: -1, x == y: 0
        """
        # 排序元素预处理
        x = preprocess_func(x)
        y = preprocess_func(y)

        """
        自定义的排序规则,返回值: x > y: 1, x < y: -1, x == y: 0
        """
        pass

    return sort_function


# 用法示例
# 把下列数据按每个元素中的第一个元素排列
data = [('12,34', 1), ('56,78', 1), ('3,34', 1), ('6,789', 1)]


# step 1, 编写自定义比较规则
def custom_sort(preprocess_func=lambda x: x):
    """
    自定义排序方法
    :param preprocess_func: 预处理函数,用于排序对象是元素内部的某一个元素时处理
    比如:排序对象为 : ['('a', 3), ('b', 2)] 时 preproess_func = lambda x: x[1]
    排序对象为:[2, 1, 3] 时: preprocess_func = lambda x: x 即默认,可不传
    :return: 排序函数
    """
    def sort_function(x, y):
        """
        根据 preprocess_func 定制的排序函数
        :param x:
        :param y:
        :return: x > y: 1, x < y: -1, x == y: 0
        """
        # 排序元素预处理
        x = preprocess_func(x)
        y = preprocess_func(y)

        """
        自定义的排序规则,返回值: x > y: 1, x < y: -1, x == y: 0
        """
        x_codes = [int(num) for num in x.split(',')]
        y_codes = [int(num) for num in y.split(',')]

        for i in range(len(x_codes)):
            # 如果比较 x 这一位时还没比出结果,而 y 已经没有这一位了,则说明前面一样,但 x 更长,x > y !
            if i >= len(y_codes):
                return 1

            # 比较当前位,如果一样则比较下一位
            if x_codes[i] == y_codes[i]:
                continue
            elif x_codes[i] > y_codes[i]:
                return 1
            elif x_codes[i] < y_codes[i]:
                return -1
            else:
                print('compare error')

        # 如果在上面的 x 循环中没有比较出大小,则说明 x == y 或者 y 还有一部分  x < y, 直接返回 y
        if x_codes == y_codes:
            return 0
        return -1
        pass

    return sort_function

# step2 导入 cmp_to_key
from functools import cmp_to_key
# step3 排序
print(sorted(data, key=cmp_to_key(custom_sort(lambda x: x[0]))))

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值