zoukankan      html  css  js  c++  java
  • python之自定义排序函数sorted()

     sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序比较函数的定义是,传入两个待比较的元素 x, y,如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0

    def custom_sort(x,y):
        if x>y:
            return -1
        if x<y:
            return 1
        return 0
    
    print sorted([2,4,5,7,3],custom_sort)  

    在python3以后,sort方法和sorted函数中的cmp参数被取消,此时如果还需要使用自定义的比较函数,那么可以使用cmp_to_key函数。将老式的比较函数(comparison function)转化为关键字函数(key function)。与接受key function的工具一同使用(如 sorted(), min(), max(), heapq.nlargest(), itertools.groupby())。该函数主要用来将程序转成 Python 3 格式的,因为 Python 3 中不支持比较函数。

    def custom_sorted(x,y):
        if x>y:
            return -1
        if x<y:
            return 1
        return 0
    
    print(sorted([2,3,1,5,4],key=cmp_to_key(custom_sorted)))

     微信扫码,介绍更全面详细。

  • 相关阅读:
    doc
    doc
    doc
    doc
    doc
    doc
    doc
    doc
    java基础知识系列--- 反射,注解,泛型,内省
    CCProcxy代理服务器的配置使用
  • 原文地址:https://www.cnblogs.com/xuxianshen/p/10257380.html
Copyright © 2011-2022 走看看