Python教程-Python 中的 max() 函数

在本教程中,我们将讨论 Python 编程语言中的 max() 函数以及如何使用它。我们还将考虑各种示例,以便更好地理解。
所以,让我们开始吧。
理解 Python max() 函数
Python 中的 max() 函数返回可迭代对象中的最大数据元素。我们还可以使用这个函数来在多个参数之间找到最大的数据元素。
Python 的 max() 函数有两种不同的形式:
- 使用可迭代对象作为参数的 max() 函数
- 使用对象作为参数的 max() 函数
带有可迭代参数的 max() 函数
我们可以使用以下语法来查找可迭代对象中的最大数据元素:
语法:
max(iterable, *iterables, key, default)
参数:
- iterable: 这是可迭代对象,例如元组、列表、字典、集合等。
- *iterables (可选): 这是可选参数,指示多个可迭代对象。
- key (可选): 这也是一个可选参数。当传递了可迭代对象并且基于其返回值进行比较时,此参数起作用。
- default (可选): 这是另一个可选参数,为函数提供指定的可迭代对象为空时的默认值。
让我们考虑一个基于此方法的示例,以找到列表中的最大元素。
示例 1
# creating a list
my_digits = [12, 3, 8, 4, 15, 13, 10, 2, 9, 11]
# using the max() function
large = max(my_digits)
# printing the result
print("The largest number in the list:", large)
输出:
The largest number in the list: 15
解释:
在上面的代码片段中,我们创建了一个名为 my_digits 的列表。然后,我们在列表上使用了 max() 函数,以获取列表中的最大元素。最后,我们为用户打印了结果。
如果可迭代对象中的数据元素是字符串,max() 函数将返回最大的元素(按字母顺序排列)。
让我们考虑一个示例,基于列表中最大的字符串。
示例 2
# creating a list
my_strings = ["Apple", "Mango", "Banana", "Papaya", "Orange"]
# using the max() function
large_str = max(my_strings)
# printing the result
print("The largest string in the list:", large_str)
输出:
The largest string in the list: Papaya
解释:
在上面的代码片段中,我们定义了一个名为 my_strings 的列表,其中包含各种字符串。然后,我们在列表上使用了 max() 函数,以找到最大的字符串元素,并将其打印给用户。
通常,对于字典,max() 函数将返回具有最大键的键。我们还可以使用 key 参数来查找具有最大值的键。
让我们考虑一个示例,演示如何在字典中使用 max() 函数。
示例 3
# creating a list
my_dict = {1 : 1, -3 : 9, 2 : 4, -5 : 25, 4 : 16}
# using the max() function to find largest key
key_1 = max(my_dict)
# printing the resultant key
print("The largest key in the dictionary:", key_1)
# using the key() function to find the key with largest value
key_2 = max(my_dict, key = lambda x : my_dict[x])
# printing the resultant key
print("The Key of the largest value in the dictionary:", key_2)
# printing the largest value
print("The largest value in the dictionary:", my_dict[key_2])
输出:
The largest key in the dictionary: 4
The Key of the largest value in the dictionary: -5
The largest value in the dictionary: 25
解释:
在上面的代码片段中,我们创建了一个字典,其中包含一些键的值。然后,我们使用 max() 函数查找字典中的最大键。接着,我们使用 max() 函数查找具有最大值的键,并将其打印给用户。
此外,我们可以看到在上述示例中的 max() 函数的第二个语句中,我们在 key 参数中传递了一个 lambda 函数。
key = lambda x : my_dict[x]
该函数将返回字典的值。基于返回的值,max() 函数将返回具有最大值的键。
需要记住的要点:
如果将空迭代器传递给该函数,将引发 ValueError 异常。为了避免此异常,我们可以在函数中包括 default 参数。
在多个迭代器的情况下,将从指定迭代器返回最大元素。
使用对象参数的 max() 函数
我们可以使用以下语法来在多个参数之间查找最大的对象。
语法:
max(arg1, arg2, *args, key)
参数:
- arg1: 这是一个对象,例如数字、字符串等。
- arg2: 这也是一个对象,例如数字、字符串等。
- *args (可选): 这是用于更多对象的可选参数。
- key (可选): 这也是一个可选参数,当传递了每个参数并且基于其返回值进行比较时起作用。
因此,max() 函数帮助我们在多个对象之间找到最大的元素。让我们考虑一个示例,以找到给定数字中的最大数字。
示例:
# using the max() function with objects as numbers
large_num = max(10, -4, 5, -3, 13)
# printing the result
print("The largest number:", large_num)
输出:
The largest number: 13
解释:
在上面的代码片段中,我们使用 max() 函数来查找指定对象作为参数的最大元素,并将结果打印给用户。