# Python `max()`函數
> 原文: [https://thepythonguru.com/python-builtin-functions/max/](https://thepythonguru.com/python-builtin-functions/max/)
* * *
于 2020 年 1 月 7 日更新
* * *
`max()`函數返回最大的輸入值。
其語法如下:
```py
max(iterable[, default=obj, key=func]) -> value
```
| 參數 | 描述 |
| --- | --- |
| `iterable`(必填) | 可迭代對象,例如字符串,列表,元組等。 |
| `default`(可選) | 如果可迭代對象為空,則返回默認值。 |
| `key`(可選) | 它引用單個參數函數以自定義排序順序。 該函數應用于迭代器上的每個項目。 |
要么
```py
max(a,b,c, ...[, key=func]) -> value
```
| 參數 | 描述 |
| --- | --- |
| `a, b, c ...` | 比較項目 |
| `key`(可選) | 它引用單個參數函數以自定義排序順序。 該函數應用于迭代器上的每個項目。 |
如果以可迭代方式調用`max()`,它將返回其中的最大項。 如果可迭代對象為空,則返回`default`值,否則引發`ValueError`異常。
如果使用多個參數調用`max()`,它將返回最大的參數。
讓我們看一些例子:
**示例 1** :以可迭代方式調用`max()`
```py
>>>
>>> max("abcDEF") # find largest item in the string
'c'
>>>
>>>
>>> max([2, 1, 4, 3]) # find largest item in the list
4
>>>
>>>
>>> max(("one", "two", "three")) # find largest item in the tuple
'two'
>>>
>>>
>>> max({1: "one", 2: "two", 3: "three"}) # find largest item in the dict
3
>>>
>>>
>>> max([]) # empty iterable causes ValueError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>>
>>>
>>> max([], default=0) # supressing the error with default value
0
>>>
```
試試看:
```py
# find largest item in the string
print(max("abcDEF"))
# find largest item in the list
print(max([2, 1, 4, 3]))
# find largest item in the tuple
print(max(("one", "two", "three")))
'two'
# find largest item in the dict
print(max({1: "one", 2: "two", 3: "three"}))
3
# empty iterable causes ValueError
# print(max([]))
# supressing the error with default value
print(max([], default=0))
```
**示例 2** :使用多個參數調用`max()`
```py
>>>
>>> max(20, 10, 30, -5)
30
>>>
>>>
>>> max("c", "b", "a", "Y", "Z")
'c'
>>>
>>>
>>> max(3.14, -9.91, 2.41)
3.14
>>>
```
試圖在不同類型的對象中找到最大值會導致錯誤。
```py
>>>
>>> max(10, "pypi")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
>>>
>>>
>>> max(5, [-10, 55])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: list() > int()
>>>
```
## 自定義排序順序
* * *
為了自定義排序順序,我們使用`key`命名參數。 它的工作原理類似于 [sorted()](/python-builtin-functions/sorted/)函數的`key`命名參數。
這是一個使用鍵參數使字符串比較區分大小寫的示例。
```py
>>>
>>> max("c", "b", "a", "Y", "Z")
'c'
>>>
>>> max("c", "b", "a", "Y", "Z", key=str.lower)
'Z'
>>>
```
試一試:
```py
print(max("c", "b", "a", "Y", "Z"))
print(max("c", "b", "a", "Y", "Z", key=str.lower))
```
以下是另一個示例,其中我們根據字符串的長度而不是其 ASCII 值比較字符串。
```py
>>>
>>> max(("python", "lua", "ruby"))
'ruby'
>>>
>>>
>>> max(("python", "lua", "ruby"), key=len)
'python'
>>>
```
試一試:
```py
print(max(("python", "lua", "ruby")))
print(max(("python", "lua", "ruby"), key=len))
```
還存在一個名為[`min()`](/python-builtin-functions/min/)的互補函數,該函數查找最低的輸入值。
* * *
* * *
- 初級 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 轉儲對象