Python 内建函数 - sorted(iterable[, key][, reverse])
- Manual
- 直譯
- 實(shí)例
- 基本排序
- key函數(shù)
- operator模塊函數(shù)
- 升序和降序
- 排序穩(wěn)定性和復(fù)雜排序
- 其他
- 拓展閱讀
Manual
Return a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
Use functools.cmp_to_key() to convert an old-style cmp function to a key function.
The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
For sorting examples and a brief sorting tutorial, see Sorting HOW TO.
直譯
根據(jù)iterable中的項(xiàng)返回一個新排序的列表。
這里有兩個可選參數(shù),其必須指定為關(guān)鍵字參數(shù)。
- key指定某個參數(shù)的函數(shù),它可以用于從每個列表元素中提取比較鍵,例如key=str.lower。默認(rèn)值為None(直接比較元素)。
- reverse是一個布爾值,如果設(shè)置為True,列表的元素會將每個比較反置進(jìn)行排列。reverse=true則是倒序(從大到小),reverse=false則是順序(從小到大),默認(rèn)是reverse=false
內(nèi)建sorted()函數(shù)可以保證穩(wěn)定,如果它保證不改變元素的相對順序,那么排序就是穩(wěn)定的。相對順序的比較恒等,對于多次傳遞下的排序很有用(例如:按部門排序,然后按工資等級排序)
實(shí)例
實(shí)例摘自官方手冊
基本排序
# 簡單排序 >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] # list.sort()方法,該方法僅對列表定義。 >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] # sorted()支持任何迭代形式 >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) [1, 2, 3, 4, 5]key函數(shù)
list.sort()和sorted()都有key參數(shù),用來指定一個函數(shù),并對每個列表元素對象調(diào)用該函數(shù)進(jìn)行比較。
# 小寫字符串比較,key=str.lower >>> sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']key參數(shù)的值應(yīng)該是一個函數(shù),其獲取一個單獨(dú)的參數(shù),并返回一個用于排序目的鍵。這個技術(shù)執(zhí)行速度快,因?yàn)槊總€輸入記錄只調(diào)用一次key函數(shù)。
常見模式式排序復(fù)雜對象,會使用一些對象的索引作為鍵,例如:
>>> >>> student_tuples = [ ... ('john', 'A', 15), ... ('jane', 'B', 12), ... ('dave', 'B', 10), ... ] >>> sorted(student_tuples, key=lambda student: student[2]) # 依照年齡排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]對于有已命名屬性的對象,可以使用相同的技術(shù),例如:
>>> >>> class Student: ... def __init__(self, name, grade, age): ... self.name = name ... self.grade = grade ... self.age = age ... def __repr__(self): ... return repr((self.name, self.grade, self.age)) >>> >>> student_objects = [ ... Student('john', 'A', 15), ... Student('jane', 'B', 12), ... Student('dave', 'B', 10), ... ] >>> sorted(student_objects, key=lambda student: student.age) # 依照年齡排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]operator模塊函數(shù)
上面展示的是很常見的key函數(shù)模式,因此Python提供了便捷的函數(shù)來使訪問器函數(shù)更簡單、更迅速,operator模塊有itemgetter()、attrgetter()和methodcaller()函數(shù)。
使用這些函數(shù),上面的實(shí)例可以變得更簡單快速:
>>> >>> from operator import itemgetter, attrgetter >>> >>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> >>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]operator模塊函數(shù)允許多層級排序,例如,先按等級排序,然后按年齡:
>>> >>> sorted(student_tuples, key=itemgetter(1,2)) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] >>> >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]升序和降序
list.sort()和sorted()都接受reverse參數(shù)(布爾值),這用于標(biāo)識降序排序,例如:以反向年齡順序獲取學(xué)生數(shù)據(jù):
>>> >>> sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> >>> sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]排序穩(wěn)定性和復(fù)雜排序
排序可以保證穩(wěn)定性,這意味著如果多個記錄具有相同的鍵,它們原來的順序是受保護(hù)的。
>>> >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> sorted(data, key=itemgetter(0)) [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]注意兩條blue記錄保持了它們原有的順序,即(‘blue’, 1) 是確保在(‘blue’, 2)之前的。
這條神奇的屬性可以讓你在一系列的排序級內(nèi)建立復(fù)雜排序,例如:以年級降序排列學(xué)生數(shù)據(jù),然后升序排列年齡。因此先做年齡排序,然后再使用年級排序:
>>> >>> s = sorted(student_objects, key=attrgetter('age')) # 以第二個鍵排序 >>> sorted(s, key=attrgetter('grade'), reverse=True) # 現(xiàn)在以第一個鍵降序排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]Python的多重排序使用了Timsort算法,感興趣的同學(xué)可以自行查找資料。
其他
- 對于本地化識別的排序,為key函數(shù)使用locale.strxfrm(),或?yàn)楸容^函數(shù)使用locale.strcoll()。
- reverse參數(shù)仍然可以保持排序的穩(wěn)定性(因此同等鍵的記錄可以保持原始順序)。有趣的是,可以通過使用內(nèi)建reversed()函數(shù)兩次來模擬這個效果:
- 當(dāng)在兩個對象間進(jìn)行比較時,排序程序會使用\ lt(),因此定義一個\ lt()方法將一個標(biāo)準(zhǔn)排列順序添加到類中,會使排序變得簡單:
- Key函數(shù)不需要直接依賴排序的對象,它也可以訪問外部資源。例如:如果對字典中學(xué)生年級排序,它們可以用分離的學(xué)生名列表排列。
拓展閱讀
operator
itemgetter()
attrgetter()
methodcaller()
locale.strxfrm()
locale.strcoll()
reversed()
總結(jié)
以上是生活随笔為你收集整理的Python 内建函数 - sorted(iterable[, key][, reverse])的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos7下使用kubeadm安装k
- 下一篇: python进程监控并重启