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

0 0
原创粉丝点击