min()
函数返回可迭代对象中最小的项。它也可以用于查找两个或更多参数中的最小项。
示例
numbers = [9, 34, 11, -4, 27]
# find the smallest number
min_number = min(numbers)
print(min_number)
# Output: -4
min()
函数有两种形式
# to find the smallest item in an iterable
min(iterable, *iterables, key, default)
# to find the smallest item between two or more objects
min(arg1, arg2, *args, key)
1. 带有可迭代参数的 min()
min() 语法
以下是 min()
函数的语法
min(iterable, *iterables, key, default)
min() 参数
- iterable - 一个可迭代对象,例如 列表、元组、集合、字典 等。
- *iterables (可选) - 任意数量的可迭代对象;可以多于一个
- key (可选) - 关键函数,可迭代对象会传递给它,并根据其返回值进行比较
- default (可选) - 如果给定的可迭代对象为空,则为默认值
min() 返回值
min()
从可迭代对象中返回最小的元素。
示例 1:获取列表中最小的项
number = [3, 2, 8, 5, 10, 6]
smallest_number = min(number);
print("The smallest number is:", smallest_number)
输出
The smallest number is: 2
如果可迭代对象中的项是字符串,则返回最小的项(按字母顺序排序)。
示例 2:列表中最小的字符串
languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);
print("The smallest string is:", smallest_string)
输出
The smallest string is: C Programming
在字典的情况下,min()
返回最小的键。让我们使用 key
参数,以便我们可以找到字典中具有最小值的键。
示例 3:字典中的 min()
square = {2: 4, 3: 9, -1: 1, -2: 4}
# the smallest key
key1 = min(square)
print("The smallest key:", key1) # -2
# the key whose value is the smallest
key2 = min(square, key = lambda k: square[k])
print("The key with the smallest value:", key2) # -1
# getting the smallest value
print("The smallest value:", square[key2]) # 1
输出
The smallest key: -2 The key with the smallest value: -1 The smallest value: 1
在第二个 min()
函数中,我们向 key
参数传递了一个 lambda 函数。
key = lambda k: square[k]
该函数返回字典的值。根据这些值(而不是字典的键),计算出具有最小值的键。
几点注意事项
- 如果我们传递一个空的迭代器,会引发
ValueError
异常。为避免这种情况,我们可以传递 default 参数。 - 如果我们传递多个迭代器,则返回给定迭代器中最小的项。
2. 没有可迭代对象的 min()
min() 语法
以下是 min() 函数的语法
min(arg1, arg2, *args, key)
min() 参数
- arg1 - 一个对象;可以是数字、字符串等。
- arg2 - 一个对象;可以是数字、字符串等。
- *args (可选) - 任意数量的对象
- key (可选) - 关键函数,每个参数都传递给它,并根据其返回值进行比较
基本上,min()
函数可以查找两个或更多对象中的最小项。
min() 返回值
min()
返回传递给它的多个参数中的最小参数。
示例 4:查找给定数字中的最小值
result = min(4, -5, 23, 5)
print("The minimum number is:", result)
输出
The minimum number is -5
如果你需要找到最大的项,可以使用 Python max() 函数。