對於python 列表,有一個方法 list.sort() ,另外還有一個內置函數sorted()python
list.sort() 是對自己排序,不會產生新的對象。而sorted 接收一個可迭代對象,返回一個新的排好序的list函數
Help on built-in function sorted in module builtins: 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 customize the sort order, and the reverse flag can be set to request the result in descending order
>>> help(list.sort)
Help on method_descriptor:
sort(...)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
list.sort() 會把原始列表修改,return None ,當你不須要原始列表的時候,這個方法會更有效率。ui
>>> a=[3,5,2,1] >>> a.sort() >>> a [1, 2, 3, 5]
sorted() 這個方法用起來比較方便spa
>>> sorted([6,3,8,12,4]) [3, 4, 6, 8, 12] >>>
sorted() 接收可迭代對象code
eg.對象
好比blog
>>> dic={4:'a',2:'b',3:'A',1:'h'} >>> sorted(dic) [1, 2, 3, 4]
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element
prior to making comparisons排序
list.sort()和sorted()都有一個關鍵參數來指定在每一個列表元素上被調用的函數在進行比較以前。ip
for example:ci
>>> sorted("This is a test string from Andrew".split(), key=str.lower) ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
The value of the key parameter should be a function that takes a single argument and returns a key to use
for sorting purposes. This technique is fast because the key function is called exactly once for each input
record
key 參數的值應該是一個函數對象,這個函數對象帶一個參數,返回一個key,這個key 就是排序的標準,
class Student(object): 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)) ls_grade = sorted([ Student('join',90,15), Student('alex',87,13), Student('eleven',100,17) ],key=lambda stu:stu.grade) ls_age = sorted([ Student('join',90,15), Student('alex',87,17), Student('eleven',100,14) ],key=lambda stu:stu.age) print(ls_grade) print(ls_age)
默認是升序排序
reverse 默認是false ,若是是true ,那就是降序排列
sorted 和list.sort() 的排序是穩定排序