python3中sorted函數(shù)取消了對cmp的支持(為了提高性能),現(xiàn)在Python3中sorted()函數(shù)的原型為: 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參數(shù)指定排序規(guī)則,key也是接受一個函數(shù),不同的是,這個函數(shù)只接受一個元素,形式如下 def f(a): return len(a) key接受的函數(shù)返回值,表示此元素的權(quán)值,sort將按照權(quán)值大小進行排序
reverse默認是false,升序排列。reverse=True時倒序排列 例如:
string='aADFef166HG62dahh3Bt6RS7Dw'b=list(filter(str.isalpha,string))PRint(b)c=sorted(b)print(c)結(jié)果:其中 字母排序"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]))輸出:根據(jù)年齡升序[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]先看一下Boolean value 的排序: print(sorted([True,Flase]))===>結(jié)果[False,True] Boolean 的排序會將 False 排在前,True排在后 .
例3:一到面試題: list1=[7, -8, 5, 4, 0, -2, -5] 要求1.正數(shù)在前負數(shù)在后 2.整數(shù)從小到大 3.負數(shù)從大到小 解題思路:先按照正負排先后,再按照大小排先后
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]一個經(jīng)典的復(fù)雜例子 這是一個字符串排序,排序規(guī)則:小寫<大寫<奇數(shù)<偶數(shù) s = ‘a(chǎn)sdf234GDSdsf23’ #排序:小寫-大寫-奇數(shù)-偶數(shù) print(“”.join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x)))) 原理:先比較元組的第一個值,F(xiàn)ALSE
新聞熱點
疑難解答