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