码迷,mamicode.com
首页 > 其他好文 > 详细

sorted函数的参数

时间:2018-07-20 22:29:53      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:des   匿名   people   div   lex   nat   函数   就是   16px   

首先附上sorted函数的官方文档说明

def sorted(*args, **kwargs): # real signature unknown
    """
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    pass

解释一下就是,sorted函数有可以有三个主要参数,第一个是iterable 可迭代对象,第二个key函数,就是自定义一个函数,可以命令他依据什么来排序,第三个是reverse,可以控制其排序结果是升序还是降序

附上一段代码:

people = [{name:alex, age:28},
          {name:s1, age:19},
          {name:s2, age:20}]

t = sorted(people, key = lambda dic:dic["age"])

print(t)

people是一个列表,可迭代对象,key使用的是lambda匿名函数,此匿名函数根据字典中的age键所对应的值的大小进行排序,默认参数为升序

所以结果为:

[{name: s1, age: 19}, {name: s2, age: 20}, {name: alex, age: 28}]

 

sorted函数的参数

标签:des   匿名   people   div   lex   nat   函数   就是   16px   

原文地址:https://www.cnblogs.com/hexiaoqi/p/9343733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!