list.sort 方法會就地排序列表,也就是說不會把原列表復(fù)制一份。這也是這個方法的返回值是 None 的原因,提醒你本方法不會新建一個列表。在這種情況下返回 None 其實是Python 的一個慣例:如果一個函數(shù)或者方法對對象進行的是就地改動,那它就應(yīng)該返回None,好讓調(diào)用者知道傳入的參數(shù)發(fā)生了變動,而且并未產(chǎn)生新的對象。例如,random.shuffle
函數(shù)也遵守了這個慣例。
用返回 None 來表示就地改動這個慣例有個弊端,那就是調(diào)用者無法將其串聯(lián)起來。而返回一個新對象的方法(比如說 str 里的所有方法)則正好相反,它們可以串聯(lián)起來調(diào)用,從而形成連貫接口(fluent interface)。詳情參見維基百科中有關(guān)連貫接口的討論(https://en.wikipedia.org/wiki/Fluent_interface)。
與 list.sort 相反的是內(nèi)置函數(shù) sorted,它會新建一個列表作為返回值。這個方法可以接受任何形式的可迭代對象作為參數(shù),甚至包括不可變序列或生成器(見第 14 章)。而不管sorted 接受的是怎樣的參數(shù),它最后都會返回一個列表。不管是 list.sort 方法還是 sorted 函數(shù),都有兩個可選的關(guān)鍵字參數(shù)。
-
reverse
如果被設(shè)定為 True,被排序的序列里的元素會以降序輸出(也就是說把最大值當作最小值來排序)。這個參數(shù)的默認值是 False。 -
key
一個只有一個參數(shù)的函數(shù),這個函數(shù)會被用在序列里的每一個元素上,所產(chǎn)生的結(jié)果將是排序算法依賴的對比關(guān)鍵字。比如說,在對一些字符串排序時,可以用 key=str.lower 來實現(xiàn)忽略大小寫的排序,或者是用 key=len 進行基于字符串長度的排序。這個參數(shù)的默認值是恒等函數(shù)(identity function),也就是默認用元素自己的值來排序。
可選參數(shù) key 還可以在內(nèi)置函數(shù) min() 和 max() 中起作用。另外,還有些標準庫里的函數(shù)也接受這個參數(shù),像 itertools.groupby() 和 heapq.nlargest() 等。
下面通過幾個小例子來看看這兩個函數(shù)和它們的關(guān)鍵字參數(shù):文章來源:http://www.zghlxwxcb.cn/news/detail-800456.html
>>> fruits = ['grape', 'raspberry', 'apple', 'banana']
>>> sorted(fruits)
['apple', 'banana', 'grape', 'raspberry']
>>> fruits
['grape', 'raspberry', 'apple', 'banana']
>>> sorted(fruits, reverse=True)
['raspberry', 'grape', 'banana', 'apple']
>>> sorted(fruits, key=len)
['grape', 'apple', 'banana', 'raspberry']
>>> sorted(fruits, key=len, reverse=True)
['raspberry', 'banana', 'grape', 'apple']
>>> fruits
['grape', 'raspberry', 'apple', 'banana']
>>> fruits.sort()
>>> fruits
['apple', 'banana', 'grape', 'raspberry']
sorted
和 list.sort
背后的排序算法是 Timsort
,它是一種自適應(yīng)算法
,會根據(jù)原始數(shù)據(jù)的順序特點交替
使用插入排序
和歸并排序
,以達到最佳效率
。這樣的算法被證明是很有效的,因為來自真實世界的數(shù)據(jù)通常是有一定的順序特點的。維基百科上有一個條目是關(guān)于這個算法的(https://en.wikipedia.org/wiki/Timsort
)。文章來源地址http://www.zghlxwxcb.cn/news/detail-800456.html
到了這里,關(guān)于python list.sort方法和內(nèi)置函數(shù)sorted的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!