# Python `sorted()`函數
> 原文: [https://thepythonguru.com/python-builtin-functions/sorted/](https://thepythonguru.com/python-builtin-functions/sorted/)
* * *
于 2020 年 1 月 7 日更新
* * *
`sorted()`內置函數允許我們對數據進行排序。 它接受一個可迭代對象,并返回一個包含來自可迭代對象的項目的排序列表。 默認情況下,它以升序排序。
`sorted()`函數的語法如下:
**語法**:`sorted(iterable, key=None, reverse=False)`
| 參數 | 描述 |
| --- | --- |
| `iterable` | (必需)可迭代地進行排序,例如字符串,列表,字典,元組等。 |
| `key`,(可選) | 它引用單個參數函數以自定義排序順序。 該函數應用于迭代器上的每個項目。 默認情況下,此參數設置為`None`。 |
| `reverse` | (可選)布爾值標志以反轉排序順序。 默認為`False`。 |
如果可迭代對象中的項目是字符串,則將按字母順序對其進行排序。 另一方面,如果它們是數字,則將按數字順序對其進行排序。
這是一個例子:
```py
>>>
>>> fruits = ['lime', 'blueberry', 'plum', 'avocado']
>>>
>>> sorted(fruits) # default sorting, in ascending order
['avocado', 'blueberry', 'lime', 'plum']
>>>
>>>
>>> sorted(fruits, reverse=True) # reverse the sorting
['plum', 'lime', 'blueberry', 'avocado']
>>>
>>>
>>> ages = [45, 11, 30, 20, 55]
>>>
>>> sorted(ages)
[11, 20, 30, 45, 55]
>>>
>>> sorted(ages, reverse=True)
[55, 45, 30, 20, 11]
>>>
```
試試看:
```py
fruits = ['lime', 'blueberry', 'plum', 'avocado']
print(sorted(fruits)) # default sorting, in ascending order
print(sorted(fruits, reverse=True)) # reverse the sorting
ages = [45, 11, 30, 20, 55]
print(sorted(ages))
print(sorted(ages, reverse=True))
```
請注意,`sorted()`返回一個包含可迭代項的新列表。 它不會更改過程中的原始可迭代項。
```py
>>>
>>> fruits # fruit list is same as before
['lime', 'blueberry', 'plum', 'avocado']
>>>
>>>
>>> ages # ages list is same as before
[45, 11, 30, 20, 55]
>>>
```
試一試:
```py
fruits = ['lime', 'blueberry', 'plum', 'avocado']
ages = [45, 11, 30, 20, 55]
print(sorted(fruits)) # default sorting, in ascending order
print(sorted(fruits, reverse=True)) # reverse the sorting
print(fruits)
print(ages)
```
以下是一些其他示例,顯示`sorted()`如何與其他 Python 類型一起使用。
## 帶字符串的`sorted()`
* * *
```py
>>>
>>> name = "Alfred Hajos"
>>>
>>> sorted(name)
[' ', 'A', 'H', 'a', 'd', 'e', 'f', 'j', 'l', 'o', 'r', 's']
>>>
>>>
>>> sorted(name, reverse=True)
['s', 'r', 'o', 'l', 'j', 'f', 'e', 'd', 'a', 'H', 'A', ' ']
>>>
```
試一試:
```py
name = "Alfred Hajos"
print(sorted(name))
print(sorted(name, reverse=True))
```
請注意,在第一個`sorted()`調用`A`的結果出現在`a`之前。 這是因為`A`的 ASCII 值為 65,`a`的 ASCII 值為 97。出于相同的原因,空格字符(`' '`)的 ASCII 值 32 出現在`A`之前。
## 帶元組的`sorted()`
* * *
```py
>>>
>>> t = ( 'ff', 'xx', 'gg', 'aa')
>>>
>>> sorted(t)
['aa', 'ff', 'gg', 'xx']
>>>
>>> sorted(t, reverse=True)
['xx', 'gg', 'ff', 'aa']
>>>
```
試一試:
```py
t = ( 'ff', 'xx', 'gg', 'aa')
print(sorted(t))
print(sorted(t, reverse=True))
```
## 帶字典的`sorted()`
* * *
```py
>>>
>>> d = {'name': 'John', 'age': 25, 'designation': 'manager'}
>>>
>>>
>>> sorted(d)
['age', 'designation', 'name']
>>>
>>> sorted(d, reverse=True)
['name', 'designation', 'age']
>>>
>>>
>>> for k in sorted(d):
... print(k, d[k])
...
age 25
designation manager
name John
>>>
>>>
>>> for k in sorted(d, reverse=True):
... print(k, d[k])
...
name John
designation manager
age 25
>>>
```
```py
d = {'name': 'John', 'age': 25, 'designation': 'manager'}
print(sorted(d))
print(sorted(d, reverse=True))
for k in sorted(d):
print(k, d[k])
print('-'*10)
for k in sorted(d, reverse=True):
print(k, d[k])
```
## 使用命名參數`key`自定義排序順序
* * *
從上一節中我們知道,如果將`sorted()`函數應用于字符串列表,則將獲得按字母順序排序的字符串列表。
如果我們想按字符串的長度而不是字母順序排序怎么辦?
這是`key`命名參數出現的地方。
要按字符串長度排序,請按以下所示將`len()`函數的鍵命名參數設置為:
```py
>>>
>>> fruits
['lime', 'blueberry', 'plum', 'avocado']
>>>
>>> sorted(fruits) # sort by alphabetical order
['avocado', 'blueberry', 'lime', 'plum']
>>>
>>> sorted(fruits, key=len) # sort by string length
['lime', 'plum', 'avocado', 'blueberry']
>>>
>>> sorted(fruits, key=len, reverse=True) # reverse sort order
['blueberry', 'avocado', 'lime', 'plum']
>>>
```
試一試:
```py
fruits = ['lime', 'blueberry', 'plum', 'avocado']
print(fruits)
print(sorted(fruits))
print(sorted(fruits, key=len)) # sort by string length
print(sorted(fruits, key=len, reverse=True)) # reverse sort order
```
有時您可能希望使排序不區分大小寫。 我們可以通過將`key`的命名參數設置為`str.lower`函數來輕松實現此目的。
```py
>>>
>>> t = ( 'AA', 'aa', 'ZZ', 'cc', 'bb')
>>>
>>> sorted(t)
['AA', 'ZZ', 'aa', 'bb', 'cc']
>>>
>>> sorted(t, key=str.lower)
['AA', 'aa', 'bb', 'cc', 'ZZ']
>>>
```
```py
t = ( 'AA', 'aa', 'ZZ', 'cc', 'bb')
print(sorted(t))
print(sorted(t, key=str.lower))
```
這是另一個示例,該示例使用自定義函數根據其包含的元音數量對字符串列表進行排序。
```py
>>>
>>> fruits
['lime', 'blueberry', 'plum', 'avocado']
>>>
>>>
>>> def count_vowel(s):
... vowels = ('a', 'e', 'i', 'o', 'u')
... count = 0
...
... for i in s:
... if i in vowels:
... count = count + 1
...
... return count
...
>>>
>>>
>>> sorted(fruits)
['avocado', 'blueberry', 'lime', 'plum']
>>>
>>> sorted(fruits, key=count_vowel)
['plum', 'lime', 'blueberry', 'avocado']
>>>
```
試一試:
```py
fruits = ['lime', 'blueberry', 'plum', 'avocado']
def count_vowel(s):
vowels = ('a', 'e', 'i', 'o', 'u')
count = 0
for i in s:
if i in vowels:
count = count + 1
return count
print(sorted(fruits))
print(sorted(fruits, key=count_vowel))
```
您還可以在用戶定義的對象上使用`sorted()`。
```py
>>>
>>> class Employee:
... def __init__(self, name, salary, age):
... self.name = name
... self.salary = salary
... self.age = age
...
... def __repr__(self):
... return self.__str__()
...
... def __str__(self):
... return "{0}:{1}:{2}".format(self.name, self.salary, self.age)
...
>>>
>>>
>>> e1 = Employee("Tom", 20000, 32)
>>> e2 = Employee("Jane", 50000, 36)
>>> e3 = Employee("Bob", 45000, 40)
>>>
>>>
>>> emp_list = [e2, e3, e1]
>>>
>>> print(emp_list)
[Jane:50000:36, Bob:45000:40, Tom:20000:32]
>>>
```
```py
class Employee:
def __init__(self, name, salary, age):
self.name = name
self.salary = salary
self.age = age
def __repr__(self):
return self.__str__()
def __str__(self):
return "{0}:{1}:{2}".format(self.name, self.salary, self.age)
e1 = Employee("Tom", 20000, 32)
e2 = Employee("Jane", 50000, 36)
e3 = Employee("Bob", 45000, 40)
emp_list = [e2, e3, e1]
print(emp_list)
# print(sorted(emp_list))
```
如果現在在`emp_list`上調用`sorted()`,則會出現如下錯誤:
```py
>>>
>>> sorted(emp_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: Employee() < Employee()
>>>
```
**提示**:
上面的代碼不會在 Python 2 中引發任何錯誤。相反,它將根據`id()`內置函數返回的 ID 對`Employee`對象進行排序。
發生這種情況是因為 Python 不知道如何比較`Employee`對象。 我們可以通過在`Employee`類中實現[特殊方法](/python-operator-overloading/)(例如`__lt__()`,`__gt__()`等)來告訴 Python 如何比較對象。
代替定義特殊方法,我們可以顯式告訴`sorted()`函數如何使用`key`命名參數對`Employee`對象進行排序。
```py
>>>
>>> sorted(emp_list, key=lambda x: x.name) # sort Employee objects by name
[Bob:45000:40, Jane:50000:36, Tom:20000:32]
>>>
>>>
>>> sorted(emp_list, key=lambda x: x.age) # sort Employee objects by age
[Tom:20000:32, Jane:50000:36, Bob:45000:40]
>>>
>>>
>>> print(sorted(emp_list, key=lambda x: x.salary)) # sort Employee objects by salary
[Tom:20000:32, Bob:45000:40, Jane:50000:36]
>>>
```
```py
class Employee:
def __init__(self, name, salary, age):
self.name = name
self.salary = salary
self.age = age
def __repr__(self):
return self.__str__()
def __str__(self):
return "{0}:{1}:{2}".format(self.name, self.salary, self.age)
e1 = Employee("Tom", 20000, 32)
e2 = Employee("Jane", 50000, 36)
e3 = Employee("Bob", 45000, 40)
emp_list = [e2, e3, e1]
print(sorted(emp_list, key=lambda x: x.name)) # sort Employee objects by name
print(sorted(emp_list, key=lambda x: x.age)) # sort Employee objects by age
print(sorted(emp_list, key=lambda x: x.salary)) # sort Employee objects by salary
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象