在Python中使用min()和max()

在本文中,我们将学习Python标准库中包含的最小和最大函数。根据用途,可以接受无限个参数

语法

max( arg1,arg2,arg3,...........)

返回值-所有参数的最大值

错误与异常:仅在参数类型不相同的情况下,才会引发错误。比较它们时遇到错误。

让我们看看我们可以max()首先通过什么方式实现该功能。

示例

# Getting maximum element from a set of arguments passed
print("传递的参数中的最大值为:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("传递的参数中的最大值为:"+str(max('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("列表的最大元素是:"+str(max(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("元组的最大元素为:"+str(max(l)))

输出结果

传递的参数中的最大值为:7
传递的参数中的最大值为:z
列表的最大元素是:45
元组的最大元素为:91

在这里可以清楚地看到,通过使用max函数,我们可以直接获取参数之间的最大值,而无需进行任何比较操作。

同样,我们可以在min()这里实现功能

示例

# Getting maximum element from a set of arguments passed
print("传递的参数中的最小值为:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("传递的参数中的最小值为:"+str(min('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("列表的最小元素是:"+str(min(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("元组的最小元素是:"+str(min(l)))

输出结果

传递的参数中的最小值为:1
传递的参数中的最小值为:a
列表的最小元素是:1
元组的最小元素是:1

通过使用max()&之类的内置函数,min()我们可以直接获取相应的最大值和最小值,而无需实际执行逻辑来进行比较

结论

在本文中,我们学习了标准Python库中包含的max和min函数的实现。