Python3中的sorted函数
来源:互联网 发布:ubuntu双系统grub修复 编辑:程序博客网 时间:2024/05/20 00:17
参照http://blog.csdn.net/lanchunhui/article/details/50959390中的一些说法和例子。
sorted() 函数接口:
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
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可以提供自定义key函数以自定义排序顺序。
reverse flag can be set to request the result in descending order.可以设置反向标志以按降序返回结果。
参数 key 用于指定用于比较的对象,key 其实是一个函数,接收的参数是前面的可迭代对象(iterable)中的每一个元素。
这里要注意的一点是,直接对字典对象迭代(也是sorted函数默认的做法)出来的元素不是 key-value 对,而是单独的key,最终的返回是由 key 构成的 list:
>>> dic={'b':3,'a':5,'c':9,'d':2}>>> sorted(dic.items(), key=lambda x: x[1])[('d', 2), ('b', 3), ('a', 5), ('c', 9)]>>> L = [('d',2),('a',4),('b',3),('c',2)]>>> sorted(L, key=lambda x:(x[1],x[0]))[('c', 2), ('d', 2), ('b', 3), ('a', 4)]
>>> for t in dic.items():print(t)('b', 3)('a', 5)('c', 9)('d', 2)
>>> for t in dic.items():print(t[1])3592
例子:
>>>nums=[19, 7, 8, 25]
>>> index = sorted(range(len(nums)), key = lambda i: nums[i])>>> index[1, 2, 0, 3]
返回结果:range(len(nums))排序后的结果。
key函数:输入是迭代对象中range(len(nums))中的每一个元素。
nums[i]: 按照nums[i]进行排序
- Python3中的sorted函数
- Python3:sorted()函数及列表中的sort()函数
- Python3中的高阶函数(map,reduce,filter,sorted)
- python3 sort sorted 函数应用
- python3 sort sorted 函数应用
- python3 sort sorted 函数应用
- Python3中sorted函数没有cmp关键字
- Python3 基础:filter和sorted函数
- Python3学习(13)--排序函数sorted
- python3中 sort sorted 函数应用
- python3手册 中的sorted 用法详解
- Python3.X中的函数
- Python3中的input函数
- python3中的 eval函数
- Python3.x中的print()函数
- Python3:字典中的items()函数
- Python3:string中的split()函数
- python3中的groupby函数用法
- 语音聊天
- CSS
- http 长连接和短连接介绍
- RocketMQ集群搭建:从源码开始
- <q>引用文本</q>
- Python3中的sorted函数
- Android Studio真机测试中遇到的问题:Error running app:No target device found.
- 兰州骑行:黄河母亲地震博物馆天斧沙宫仁寿山湿地公园
- pip安装报错:is not a supported wheel on this platform
- 设置 Sublime Text 的 Python 开发环境
- 用objective-c写2048算法
- 初窥Linux 之 我最常用的20条命令
- JetBrains产品激活
- MySQL 使用自增ID主键和UUID 作为主键的优劣比较详细过程(500W单表)