国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python3 sorted()的用法

2019-11-08 01:05:10
字體:
供稿:網(wǎng)友

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


上一篇:Python中切片的理解

下一篇:Python初識

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 兴文县| 明溪县| 新建县| 陇南市| 宽甸| 长乐市| 特克斯县| 游戏| 灵丘县| 潜山县| 庐江县| 宜章县| 金寨县| 旅游| 安岳县| 玉门市| 息烽县| 门源| 信宜市| 金门县| 威海市| 赤城县| 日土县| 黑河市| 色达县| 阿勒泰市| 交城县| 通辽市| 车险| 灌阳县| 辛集市| 博野县| 饶平县| 阳高县| 道孚县| 乌鲁木齐县| 东港市| 兴安县| 张家界市| 大厂| 同心县|