zoukankan      html  css  js  c++  java
  • 高阶函数sorted()的用法详解

    高阶函数sorted()的用法详解

    sorted(list, key, reverse)

    list是给定的列表;

    key是排序过程调用的函数,也就是排序依据

    reverse是降序还是升序,默认为False升序,True降序

    1 l1 = [1,3,5,-2,-4,-6]
    2 l2 = sorted(l1,key=abs)
    3 print(l1)
    4 print(l2)
    5 
    6 #
    7 [1, 3, 5, -2, -4, -6]
    8 [1, -2, 3, -4, 5, -6]
    按照列表元素的绝对值进行排序
    1 l = [[1,2],[3,4,5,6],(7,),'123']
    2 print(sorted(l,key=len))
    3 
    4 #
    5 [(7,), [1, 2], '123', [3, 4, 5, 6]]
    按照列表中每个元素的长度进行排序
    1 word_dict = {'apple':20, 'love':15}
    2 sorted_word_dict = sorted(word_dict.items(), key=lambda d:d[1])
    3 print(sorted_word_dict)
    4 
    5 #
    6 [('love', 15), ('apple', 20)]
    按照词频大小进行排序
  • 相关阅读:
    SpringBoot笔记
    SpringBoot面试篇
    多线程篇
    Tomcat篇
    Redis篇
    Nginx篇
    JVM篇
    MySQL篇
    python ETL工具 pyetl
    python通用数据库操作工具 pydbclib
  • 原文地址:https://www.cnblogs.com/NumerOne/p/11645959.html
Copyright © 2011-2022 走看看