英文文檔: sorted(iterable[, key][, reverse]) Return a new sorted list from the items in iterable. Has two optional arguments which must be specified as ke ...
英文文檔:
sorted
(iterable[, key][, reverse])
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).
說明:
1. 函數功能對一個可迭代對象進行排序,返回一個排序後列表。
>>> a = sorted('dcabegf') >>> a # 返回結果是列表 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
2. 函數調用時可以提供一個可選的命名參數key,它是一個方法,預設值是None,用來指定具體排序的演算法;函數對可迭代對象每個元素使用key演算法後再排序,返回的任然是可迭代對象中的元素。
>>> a = ['a','b','d','c','B','A'] >>> a ['a', 'b', 'd', 'c', 'B', 'A'] >>> sorted(a) # 預設按字元ascii碼排序 ['A', 'B', 'a', 'b', 'c', 'd'] >>> sorted(a,key = str.lower) # 轉換成小寫後再排序,'a'和'A'值一樣,'b'和'B'值一樣 ['a', 'A', 'b', 'B', 'c', 'd']
3. 函數調用時可以提供一個可選的命名參數reverse,它的預設值是False,用來排序結果是否倒轉。
>>> a = sorted('dcabegf') >>> a ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> a = sorted('dcabegf',reverse = True) # 排序結果倒置 >>> a ['g', 'f', 'e', 'd', 'c', 'b', 'a']