python 中的sort()
函數有助于按照用戶定義的順序(升序或降序)對列表進行排序。默認情況下,排序按升序進行。
**list.sort(key=..., reverse=...)** #where key is function name
排序()參數:
這個函數有兩個可選參數。我們也可以使用排序(列表,鍵=...,反向=...)方法出于同樣的目的。不同的是sorted()
方法不改變列表并返回一個排序列表,但是sorted()
方法直接改變列表并且不返回任何值。
參數 | 描述 | 必需/可選 |
---|---|---|
反面的 | 如果為真,則排序列表反轉(或按降序) | 可選擇的 |
鍵 | 用作排序比較的關鍵字的函數 | 可選擇的 |
排序()返回值
sort()
方法不返回值。它通過更改元素的順序來更新原始列表。為了返回排序列表而不改變原始列表,我們可以使用sorted()
方法。
Python 中sort()
方法的示例
示例 1:如何在 Python 中對列表進行排序?
# alphabets list
alphabets = ['b', 'a', 'e', 'd', 'c']
# sort the alphabets
alphabets.sort()
# print alphabets
print('Sorted list:', alphabets)
輸出:
Sorted list: ['a', 'b', 'c', 'd', 'e']
例 2:如何對列表進行降序排序?
# alphabets list
alphabets = ['b', 'a', 'e', 'd', 'c']
# sort the alphabets
alphabets.sort(reverse=True)
# print alphabets
print('Sorted list in Descending order:', alphabets)
輸出:
Sorted list in Descending order: ['e', 'd', 'c', 'b', 'a']
示例 3:如何使用鍵對列表進行排序?
# take second element for sort
def second(elem):
return elem[1]
# random list
randomlist = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
randomlist.sort(key=second)
# print list
print('Sorted list:', randomlist)
輸出:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]