python3 sorted()的用法
来源:互联网 发布:ubuntu安装五笔拼音 编辑:程序博客网 时间:2024/05/08 05:07
python3中sorted函数取消了对cmp的支持(为了提高性能),现在Python3中sorted()函数的原型为:
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 customise the sort order, and thereverse flag can be set to request the result in descending order.
key参数指定排序规则,key也是接受一个函数,不同的是,这个函数只接受一个元素,形式如下
def f(a):
return len(a)
key接受的函数返回值,表示此元素的权值,sort将按照权值大小进行排序
reverse默认是false,升序排列。reverse=True时倒序排列
例如:
string='aADFef166HG62dahh3Bt6RS7Dw'b=list(filter(str.isalpha,string))print(b)c=sorted(b)print(c)结果:其中 字母排序"a'>"A" ,"A"<"B",'a'>'B'['a', 'A', 'D', 'F', 'e', 'f', 'H', 'G', 'd', 'a', 'h', 'h', 'B', 't', 'R', 'S', 'D', 'w']['A', 'B', 'D', 'D', 'F', 'G', 'H', 'R', 'S', 'a', 'a', 'd', 'e', 'f', 'h', 'h', 't', 'w']
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]print(sorted(students,key=lambda x: x[2]))输出:根据年龄升序[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
先看一下Boolean value 的排序:
print(sorted([True,Flase]))===>结果[False,True] Boolean 的排序会将 False 排在前,True排在后 .
例3:一到面试题:
list1=[7, -8, 5, 4, 0, -2, -5]
要求1.正数在前负数在后 2.整数从小到大 3.负数从大到小
解题思路:先按照正负排先后,再按照大小排先后
list1=[7, -8, 5, 4, 0, -2, -5]print(sorted(list1,key=lambda x:(x<0,abs(x))))[7, 5, 4, 0, -8, -2, -5][0, 4, 5, 7, -2, -5, -8]
一个经典的复杂例子
这是一个字符串排序,排序规则:小写<大写<奇数<偶数
s = ‘asdf234GDSdsf23’ #排序:小写-大写-奇数-偶数
print(“”.join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x))))
原理:先比较元组的第一个值,FALSE
- python3 sorted的用法
- python3 sorted()的用法
- python3手册 中的sorted 用法详解
- Python3的一些用法
- Python3:set的用法
- python3 zip的用法
- Python3.x与Python2.x关于sorted函数用法比较
- python的sorted用法
- Python sorted()的用法
- python3 多线程的基本用法
- python3 多线程的基本用法
- python3中super()的用法
- python3 counter函数的用法
- redis的sorted set用法
- map,reduce,sorted的用法
- Python 中 sorted 的用法
- Python3中的sorted函数
- Python3.5里print()的用法
- lua 语言介绍及安装
- 【转载】腾讯+华为+网易游戏面经
- NIO与Netty的Channel组件
- 历届试题 核桃的数量 (最小公倍数)
- Maven中使用mysql数据库
- python3 sorted()的用法
- 100亿数据1万属性数据架构设计
- 用eclipse集成opencv+java最高效的方法
- 多级菜单实现等级自动划分
- 通信中调制概念的理解和分类
- JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法
- Linux Epoll vs Windows IOCP
- python random随机数
- UITabBar背景、icon图标颜色、被选中背景设置以及隐藏UITabBar的方式