于 2020 年 1 月 7 日更新
min()函数返回最小的输入值。
其语法如下:
min(iterable[, default=obj, key=func]) -> value
| 参数 | 描述 |
|---|---|
iterable(必填) |
可迭代对象,例如字符串,列表,元组等。 |
default(可选) |
如果可迭代对象为空,则返回默认值。 |
key(可选) |
它引用单个参数函数以自定义排序顺序。 该函数应用于迭代器上的每个项目。 |
要么
min(a, b, c, ...[, key=func]) -> value
| 参数 | 描述 |
|---|---|
a, b, c ... |
比较项目 |
key(可选) |
它引用单个参数函数以自定义排序顺序。 该函数适用于每个项目。 |
如果以可迭代方式调用min(),它将返回其中的最小项。 如果可迭代对象为空,则返回default值(假设已提供),否则引发ValueError异常。
如果使用多个参数调用min(),它将返回最小的参数。
让我们看一些例子:
示例 1 :以可迭代方式调用min()
>>>>>> min("abcDEF") # find smallest item in the string'D'>>>>>>>>> min([2, -1, 4, 3]) # find smallest item in the list-1>>>>>>>>> min(("one", "two", "three")) # find smallest item in the tuple'one'>>>>>>>>> min({1: "one", 2: "two", 3: "three"}) # find smallest item in the dict1>>>>>>>>> min([]) # empty iterable causes ValueErrorTraceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: min() arg is an empty sequence>>>>>>>>> min([], default=0) # supressing the error with default value0>>>
试试看:
# find smallest item in the stringprint(min("abcDEF"))# find smallest item in the listprint(min([2, -1, 4, 3]))# find smallest item in the tupleprint(min(("one", "two", "three")))# find smallest item in the dictprint(min({1: "one", 2: "two", 3: "three"}))#print(min([])) # empty iterable causes ValueError# supressing the error with default valueprint(min([], default=0))
示例 2 :使用多个参数调用min()
>>>>>> min(20, 10, 30, -5)-5>>>>>>>>> min("c", "b", "a", "Y", "Z")'Y'>>>>>>>>> min(3.14, -9.91, 2.41)-9.91>>>
试一试:
print(min(20, 10, 30, -5))print(min("c", "b", "a", "Y", "Z"))print(min(3.14, -9.91, 2.41))
试图在不同类型的对象中找到最大值会导致错误。
>>>>>> min(10, "pypi")Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: unorderable types: str() > int()>>>>>>>>> min(5, [-10, 55])Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: unorderable types: list() > int()>>>
自定义排序顺序
为了自定义排序顺序,我们使用key命名参数。 它的工作原理类似于sorted()函数的key命名参数。
这是一个使用键参数使字符串比较区分大小写的示例。
>>>>>> min("c", "b", "a", "Y", "Z")'Y'>>>>>> min("c", "b", "a", "Y", "Z", key=str.lower)'a'>>>
试一试:
print(min("c", "b", "a", "Y", "Z"))print(min("c", "b", "a", "Y", "Z", key=str.lower))
以下是另一个示例,其中我们根据字符串的长度而不是其 ASCII 值比较字符串。
>>>>>> min(("java", "python", "z++"))'java'>>>>>> min(("java", "python", "z++"), key=len)'z++'>>>
试一试:
print(min(("java", "python", "z++")))print(min(("java", "python", "z++"), key=len))
还存在一个互补函数,称为max(),可找到最大的输入值。
