于 2020 年 1 月 7 日更新
max()函数返回最大的输入值。
其语法如下:
max(iterable[, default=obj, key=func]) -> value
| 参数 | 描述 |
|---|---|
iterable(必填) |
可迭代对象,例如字符串,列表,元组等。 |
default(可选) |
如果可迭代对象为空,则返回默认值。 |
key(可选) |
它引用单个参数函数以自定义排序顺序。 该函数应用于迭代器上的每个项目。 |
要么
max(a,b,c, ...[, key=func]) -> value
| 参数 | 描述 |
|---|---|
a, b, c ... |
比较项目 |
key(可选) |
它引用单个参数函数以自定义排序顺序。 该函数应用于迭代器上的每个项目。 |
如果以可迭代方式调用max(),它将返回其中的最大项。 如果可迭代对象为空,则返回default值,否则引发ValueError异常。
如果使用多个参数调用max(),它将返回最大的参数。
让我们看一些例子:
示例 1 :以可迭代方式调用max()
>>>>>> max("abcDEF") # find largest item in the string'c'>>>>>>>>> max([2, 1, 4, 3]) # find largest item in the list4>>>>>>>>> max(("one", "two", "three")) # find largest item in the tuple'two'>>>>>>>>> max({1: "one", 2: "two", 3: "three"}) # find largest item in the dict3>>>>>>>>> max([]) # empty iterable causes ValueErrorTraceback (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 value0>>>
试试看:
# find largest item in the stringprint(max("abcDEF"))# find largest item in the listprint(max([2, 1, 4, 3]))# find largest item in the tupleprint(max(("one", "two", "three")))'two'# find largest item in the dictprint(max({1: "one", 2: "two", 3: "three"}))3# empty iterable causes ValueError# print(max([]))# supressing the error with default valueprint(max([], default=0))
示例 2 :使用多个参数调用max()
>>>>>> max(20, 10, 30, -5)30>>>>>>>>> max("c", "b", "a", "Y", "Z")'c'>>>>>>>>> max(3.14, -9.91, 2.41)3.14>>>
试图在不同类型的对象中找到最大值会导致错误。
>>>>>> 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()函数的key命名参数。
这是一个使用键参数使字符串比较区分大小写的示例。
>>>>>> max("c", "b", "a", "Y", "Z")'c'>>>>>> max("c", "b", "a", "Y", "Z", key=str.lower)'Z'>>>
试一试:
print(max("c", "b", "a", "Y", "Z"))print(max("c", "b", "a", "Y", "Z", key=str.lower))
以下是另一个示例,其中我们根据字符串的长度而不是其 ASCII 值比较字符串。
>>>>>> max(("python", "lua", "ruby"))'ruby'>>>>>>>>> max(("python", "lua", "ruby"), key=len)'python'>>>
试一试:
print(max(("python", "lua", "ruby")))print(max(("python", "lua", "ruby"), key=len))
还存在一个名为min()的互补函数,该函数查找最低的输入值。
