sorted函数的参数

mac2022-06-30  70

首先附上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}]

 

转载于:https://www.cnblogs.com/hexiaoqi/p/9343733.html

相关资源:python3中sorted函数里cmp参数改变详解
最新回复(0)