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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。