首先附上 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}]
来源: http://www.bubuko.com/infodetail-2693409.html