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


在本文中,我们将学习 Python 标准库中包含的 min 和 max 函数。它根据用法接受无限数量的参数

语法

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

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

错误和异常:此处仅在参数不属于同一类型的情况下引发错误。比较时会遇到错误。

让我们首先看看实现 max() 函数的所有方式。

示例

 在线演示

# Getting maximum element from a set of arguments passed
print("Maximum value among the arguments passed is:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Maximum value among the arguments passed is:"+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("Maximum element of the list is:"+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("Maximum element of the tuple is:"+str(max(l)))

输出

Maximum value among the arguments passed is:7
Maximum value among the arguments passed is:z
Maximum element of the list is:45
Maximum element of the tuple is:91

在这里清楚地看到,通过使用 max 函数,我们可以在没有进行任何比较操作的情况下直接获取参数中的最大值。

同样,我们可以在此实现 min() 函数

示例

 在线演示

# Getting maximum element from a set of arguments passed
print("Minimum value among the arguments passed is:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Minimum value among the arguments passed is:"+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("Minimum element of the list is:"+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("Minimum element of the tuple is:"+str(min(l)))

输出

Minimum value among the arguments passed is:1
Minimum value among the arguments passed is:a
Minimum element of the list is:1
Minimum element of the tuple is:1

通过使用 max() 和 min() 等内置函数,我们可以在不实际实现进行比较的逻辑的情况下直接获得相应的最大值和最小值

结论

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

更新于: 2019 年 8 月 29 日

352 次浏览

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.