首页 > 其他 > 详细

sorted函数的参数

时间:2018-07-20 22:19:12      阅读:197      评论:0      收藏:0      [点我收藏+]

首先附上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函数的参数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!