Python 的 max(~)
方法有兩個用例:
-
當與可迭代對象一起使用時,它返回可迭代對象中最大的項。
-
當與多個參數一起使用時,它返回參數中最大的項。
參數
與可迭代對象一起使用
1.iterable
| iterable
用於檢索最大項目的迭代。
2. key
| function
| optional
指定排序標準的函數。該函數應采用單個參數並返回用於排序的鍵。
3. default
| object
| optional
如果提供的可迭代對象為空,則返回該對象。
與多個參數一起使用
1. arg1
| object
用於比較的對象。
2. arg2
| object
用於比較的對象。
3. args
| object
| optional
用於比較的對象數量不受限製。
4. key
| function
| optional
指定排序標準的函數。該函數應采用單個參數並返回用於排序的鍵。
返回值
返回值取決於以下情況:
案子 |
返回值 |
---|---|
與可迭代對象一起使用 |
可迭代中最大的項 |
與多個參數一起使用 |
參數中最大的項目 |
例子
與可迭代對象一起使用
返回列表 x
中的最大數字:
x = [4, 3, 9, 2, 11, 6]
max(x)
11
按字母順序返回列表 languages
中最大的項目:
languages = ['Spanish', 'French', 'English', 'Mandarin']
max(languages)
Spanish
與多個參數一起使用
要從提供的參數中返回最大的數字:
max(4, 3, 9, 2, 11, 6)
11
關鍵參數
根據 iterable 中每個元素的第二個字母的字母順序返回最大的項目:
def check_second_letter(a):
return a[1]
languages = ['Spanish', 'French', 'English', 'Mandarin']
max(languages, key=check_second_letter)
'French'
返回 French
,因為它的第二個字母 'r'
是按字母順序排列的最高字母。
默認參數
如果 languages
可迭代為空,則返回 'List is Empty'
:
languages = []
max(languages, default='List is Empty')
List is Empty
請注意,default
參數僅適用於 max
方法與可迭代輸入一起使用的情況。
相關用法
- Python Tkinter maxsize()用法及代碼示例
- Python max()用法及代碼示例
- Python NumPy maximum方法用法及代碼示例
- Python string max()用法及代碼示例
- Python max() and min()用法及代碼示例
- Python matplotlib.patheffects.withTickedStroke用法及代碼示例
- Python matplotlib.axes.Axes.step用法及代碼示例
- Python matplotlib.texmanager.TexManager.get_rgba用法及代碼示例
- Python matplotlib.backend_bases.MouseEvent用法及代碼示例
- Python matplotlib.collections.RegularPolyCollection.set_hatch用法及代碼示例
- Python numpy ma.MaskedArray.view用法及代碼示例
- Python matplotlib.patches.Rectangle用法及代碼示例
- Python matplotlib._api.deprecation.deprecated用法及代碼示例
- Python matplotlib._api.select_matching_signature用法及代碼示例
- Python matplotlib.figure.Figure.align_xlabels用法及代碼示例
- Python matplotlib.pyplot.step()用法及代碼示例
- Python matplotlib.figure.SubFigure.add_subplot用法及代碼示例
- Python matplotlib.collections.BrokenBarHCollection.set_hatch用法及代碼示例
- Python math.cos()用法及代碼示例
- Python math.cosh()用法及代碼示例
- Python matplotlib.collections.PolyCollection.sticky_edges用法及代碼示例
- Python matplotlib.axes.Axes.barbs用法及代碼示例
- Python matplotlib.textpath.TextToPath.get_text_path用法及代碼示例
- Python math.acosh()用法及代碼示例
- Python main()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python | max method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。