當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python sorted()用法及代碼示例

Python sorted() 函數用於對元素進行排序。默認情況下,它按升序對元素進行排序,但也可以降序排序。它接受四個參數並按排序順序返回集合。在字典的情況下,它隻對鍵進行排序,而不對值進行排序。該函數的簽名如下。

簽名

sorted (iterable[, cmp[, key[, reverse]]])

參數

iterable: 執行排序的集合。

cmp:自定義比較函數。默認值為無。

key:一個函數。

reverse:以相反的順序獲取排序的集合。

返回

它返回一個唯一的整數。

讓我們看一些 id() 函數的例子來理解它的函數。

Python sorted() 函數示例 1

在此示例中,我們正在對字符串對象進行排序以了解該函數。

# Python sorted() function example
str = "javatpoint" # declaring string
# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)

輸出:

['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']

Python sorted() 函數示例2

我們可以使用此函數對任何可迭代對象(如列表、元組和字典)進行排序。請參閱下麵的示例。

# Python sorted() function example
li = [2003,56,98,659,622,1002,3652]
tupl = (232,2500,3698,5264,2578,21)
dic = {3:'Three',4:'Four',1:'One',2:'Two'}
# Calling function
lisorted  = sorted(li) # sorting list
tupsorted = sorted(tupl) # tuple 
dicsorted = sorted(dic) # dictionary
# Displaying result
print(lisorted)
print(tupsorted)
print(dicsorted)

輸出:

[56, 98, 622, 659, 1002, 2003, 3652]
[21, 232, 2500, 2578, 3698, 5264]
[1, 2, 3, 4]

Python sorted() 函數示例3

要將列表按相反順序(降序)排序,請反向傳遞 True,我們將按相反順序對列表進行排序。

# Python sorted() function example
li = [2003,56,98,659,622,1002,3652]
# Calling function
lisorted  = sorted(li, reverse = True) # Sorting list in descending order
# Displaying result
print(lisorted)

輸出:

[3652, 2003, 1002, 659, 622, 98, 56]

Python sorted() 函數示例 4

在這裏,我們通過在調用期間在鍵中傳遞 lambda 函數來對列表進行排序。

# Python sorted() function example
li = [(2,15),(3,5),(65,5),(8,5)]
# Calling function
lisorted  = sorted(li, key=lambda x:sum(x)) # Sorting list by getting sum of tuples
# Displaying result
print(lisorted)

輸出:

[(3, 5), (8, 5), (2, 15), (65, 5)]






相關用法


注:本文由純淨天空篩選整理自 Python sorted() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。