當前位置:生活全書館 >

IT科技

> sorted python

sorted python

sorted是屬於python下的一個函式,sorted()函式是用於對所有可迭代的物件進行排序操作。

它與sort 是有一定區別的,具體的區別是:

sort通常是應用在list上的方法,而sorted則能夠對所有可迭代的物件進行排序操作。

list中的sort方法一般返回的是對已經存在的列表進行操作,無返回值,但是內建函式sorted方法返回的是一個新的list,因此它並不是在原有的基礎上進行操作。

語法格式

sorted(iterable, cmp=None, key=None, reverse=False)

python sorted

引數:

iterable -- 可迭代物件。

cmp -- 比較的函式,這個具有兩個引數,引數的值都是從可迭代物件中取出,此函式必須遵守的規則為,大於則返回1,小於則返回-1,等於則返回0。

key -- 主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自於可迭代物件中,指定可迭代物件中的一個元素來進行排序。

reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(預設)。

python sorted 第2張

參考範例:

>>>a = [5,7,6,3,4,1,2]>>> b = sorted(a)       # 保留原列表>>> a [5, 7, 6, 3, 4, 1, 2]>>> b[1, 2, 3, 4, 5, 6, 7] >>> L=[('b',2),('a',1),('c',3),('d',4)]>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))   # 利用cmp函式[('a', 1), ('b', 2), ('c', 3), ('d', 4)]>>> sorted(L, key=lambda x:x[1])               # 利用key[('a', 1), ('b', 2), ('c', 3), ('d', 4)]  >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>> sorted(students, key=lambda s: s[2])            # 按年齡排序[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> sorted(students, key=lambda s: s[2], reverse=True)       # 按降序[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>>
標籤: sorted Python
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/z90nmo.html