標籤:ack lam iterable repr lex ges 效率 init cti
python - how to sort
- overview
- Key function (★★★★★)
- OPerator module functions
- asc and desc 升序和降序
Overview
對於python 列表,有一個方法 list.sort() ,另外還有一個內建函數sorted()
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 ,當你不需要原始列表的時候,這個方法會更有效率。
>>> a=[3,5,2,1]>>> a.sort()>>> a[1, 2, 3, 5]
sorted() 這個方法用起來比較方便
>>> sorted([6,3,8,12,4])[3, 4, 6, 8, 12]>>>
sorted() 接收可迭代對象
eg.
比如
>>> dic={4:‘a‘,2:‘b‘,3:‘A‘,1:‘h‘}>>> sorted(dic)[1, 2, 3, 4]
Key function
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()都有一個關鍵參數來指定在每個列表元素上被調用的函數在進行比較之前。
for example:
>>> 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)
OPerator module functions
asc and desc 升序和降序
預設是升序排序
reverse 預設是false ,如果是true ,那就是降序排列
sorted 和list.sort() 的排序是穩定排序
于洋 回到頂部
python - how to sort