zoukankan      html  css  js  c++  java
  • 7高阶函数sorted

    """
    sorted()
    运行原理:
    把可迭代数据里面的元素,一个个的拿出来,放到key这个函数在进行处理,
    并安装函数中retrun的结果进行排序,返回一个新列表
    功能: 排序
    参数:
    iterable 可迭代的数据
    reverse 可选,是否反转,默认为False不反转, True反转
    key 可选, 函数,可以是自定义函数,或内建函数

    返回值: 排序后的结果
    """

    sorted 的三种方法

    1从小到大排序

    arr = [32,54,5,-21,3,2,5]
    res = sorted(arr)
    print(res)
    
    
    E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
    [-21, 2, 3, 5, 5, 32, 54]
    

    2reverse=True 从大到小排序

    arr = [32,54,5,-21,3,2,5]
    res = sorted(arr,reverse=True)
    print(res)
    
    E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
    [2, 3, -5, 21, 32, 54]
    

    3使用abs函数(求绝对值),作为sorted的key关键字参数使用

    arr = [32, 54, -5, 21, 3, 2]
    res = sorted(arr, key=abs)
    print(res)
    
    E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
    [2, 3, -5, 21, 32, 54]
    

    4使用自定义函数,当作key的关键字参数

    def func(num):
        return num % 4
    
    arr = [32,54,5,21,3,2,5]
    
    # 在sorted函数中使用自定义函数对数据进行出来处理
    res = sorted(arr,key=func)
    print(res)
    
    E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
    [32, 5, 21, 5, 54, 2, 3]
    

    5使用匿名函数当作sorted的参数

    arr = [32,54,5,21,3,2,5]
    res = sorted(arr,key=lambda n:n%2)
    print(res)
    
    E:\python3810\python.exe D:/py/test/gao/函数-sorted.py
    [32, 54, 2, 5, 21, 3, 5]
    
  • 相关阅读:
    Struts之上传
    Struts之准备工作
    前端--关于背景、浮动和定位
    javascript学习目录
    audio和video元素
    js实现动态操作table
    jquery全选、反选、全不选
    js实现页面跳转
    10 个非常有用的 AngularJS 框架
    JavaScript 语言基础知识点总结(思维导图)
  • 原文地址:https://www.cnblogs.com/john5yang/p/15631004.html
Copyright © 2011-2022 走看看