日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python?內(nèi)置函數(shù)sorted()的用法_python

作者:Brad1994 ? 更新時(shí)間: 2022-05-27 編程語(yǔ)言

對(duì)于Python內(nèi)置函數(shù)sorted(),先拿來(lái)跟list(列表)中的成員函數(shù)list.sort()進(jìn)行下對(duì)比。在本質(zhì)上,list的排序和內(nèi)建函數(shù)sorted的排序是差不多的,連參數(shù)都基本上是一樣的。
主要的區(qū)別在于,list.sort()是對(duì)已經(jīng)存在的列表進(jìn)行操作,進(jìn)而可以改變進(jìn)行操作的列表。而內(nèi)建函數(shù)sorted返回的是一個(gè)新的list,而不是在原來(lái)的基礎(chǔ)上進(jìn)行的操作.

再來(lái),讓我們用Python自帶的幫助函數(shù)help()看看對(duì)于sorted()是怎么定義的:

?>>>help(sorted)
?
?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 customise the sort order, and the
? ? ?reverse flag can be set to request the result in descending order.

要先說(shuō)明的是, 本人用的Python版本為3.5, 所以會(huì)跟Python2的有變差。

由幫助可以看到,傳進(jìn)去一個(gè)可迭代的數(shù)據(jù),返回一個(gè)新的列表,注意,是新的列表!來(lái)看看看實(shí)例吧:

>>>g=[1,4,6,8,9,3,5]
>>>sorted(g)
Out[30]: [1, 3, 4, 5, 6, 8, 9]

>>>sorted((1,4,8,9,3,6))
Out[33]: [1, 3, 4, 6, 8, 9]

>>>sorted('gafrtp')
Out[35]: ['a', 'f', 'g', 'p', 'r', 't']

由以上可以看到,只要是可迭代對(duì)象數(shù)據(jù),都能夠進(jìn)行排序,生成一個(gè)排序后的列表。

如果想要排逆序呢?很簡(jiǎn)單,只要將可選參數(shù)reverse設(shè)置為T(mén)rue即可:

?>>>sorted((1,4,8,9,3,6), reverse=True)
?Out[36]: [9, 8, 6, 4, 3, 1]

高級(jí)用法:

有時(shí)候,我們要處理的數(shù)據(jù)內(nèi)的元素不是一維的,而是二維的甚至是多維的,那要怎么進(jìn)行排序呢?這時(shí)候,sorted()函數(shù)內(nèi)的key參數(shù)就派上用場(chǎng)了!從幫助信息上可以了解到,key參數(shù)可傳入一個(gè)自定義函數(shù)。

那么,該如何使用呢?讓我們看看如下代碼:

>>>l=[('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
>>>sorted(l, key=lambda x:x[0])
Out[39]: [('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
>>>sorted(l, key=lambda x:x[0], reverse=True)
Out[40]: [('e', 3), ('d', 4), ('c', 6), ('b', 2), ('a', 1)]
>>>sorted(l, key=lambda x:x[1])
Out[41]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
>>>sorted(l, key=lambda x:x[1], reverse=True)
Out[42]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]

這里,列表里面的每一個(gè)元素都為二維元組,key參數(shù)傳入了一個(gè)lambda函數(shù)表達(dá)式,其x就代表列表里的每一個(gè)元素,然后分別利用索引返回元素內(nèi)的第一個(gè)和第二個(gè)元素,這就代表了sorted()函數(shù)利用哪一個(gè)元素進(jìn)行排列。而reverse參數(shù)就如同上面講的一樣,起到逆排的作用。默認(rèn)情況下,reverse參數(shù)為False。

當(dāng)然,正如一開(kāi)始講到的那樣,如果想要對(duì)列表直接進(jìn)行排序操作,可以用成員方法sort()來(lái)做:

>>>l.sort(key=lambda x : x[1])
>>>l
Out[45]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
>>>l.sort(key=lambda x : x[1], reverse=True)
>>>l
Out[47]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]

對(duì)于三維及以上的數(shù)據(jù)排排序,上述方法同樣適用。

原文鏈接:https://www.cnblogs.com/brad1994/p/6697196.html

欄目分類
最近更新