当前位置: 首页>>代码示例>>用法及示例精选>>正文


Python max() and min()用法及代码示例

本文为您带来了一个非常有趣且鲜为人知的Python函数,即max()和min()。现在,与仅允许两个参数(过于严格地为float,int或char)的C++相比,这些函数不仅限于2个元素,而且可以容纳许多元素作为参数,并在其参数中支持字符串,因此也可以显示字典上最小或最大的字符串。详细功能说明如下。

max()

此函数用于计算在其参数中传递的值的最大值,在将字符串作为参数传递时,按字典顺序计算最大值。

用法:
max(a,b,c,..)
参数:
a,b,c,..:  similar type of data.
返回值:
Returns the maximum of all the arguments.
Exceptions:
Returns TypeError when conflicting types are compared.
# Python code to demonstrate the working of  
# max()  
  
# printing the maximum of 4,12,43.3,19,100 
print("Maximum of 4,12,43.3,19 and 100 is:",end="") 
print (max( 4,12,43.3,19,100 ) )

输出:


Maximum of 4,12,43.3,19 and 100 is:100

min()

此函数用于计算在其参数中传递的值的最小值,在将字符串作为参数传递时,按字典顺序计算的最小值。

用法:
min(a,b,c,..)
参数:
a,b,c,..:  similar type of data.
返回值:
Returns the minimum of all the arguments.
Exceptions:
Returns TypeError when conflicting types are compared.
# Python code to demonstrate the working of  
# min()  
  
# printing the minimum of 4,12,43.3,19,100 
print("Minimum of 4,12,43.3,19 and 100 is:",end="") 
print (min( 4,12,43.3,19,100 ) )

输出:

Minimum of 4,12,43.3,19 and 100 is:4

异常

1. TypeError:比较冲突的数据类型时,这些函数将引发TypeError。

# Python code to demonstrate the Exception of  
# min() and max() 
  
# printing the minimum of 4,12,43.3,19, "GeeksforGeeks" 
# Throws Exception 
print("Minimum of 4,12,43.3,19 and GeeksforGeeks is:",end="") 
print (min( 4,12,43.3,19,"GeeksforGeeks" ) )

输出:

Minimum of 4,12,43.3,19 and GeeksforGeeks is:

运行时错误:

Traceback (most recent call last):
  File "/home/b5da1d7f834a267f94fbbefe1b31a83c.py", line 7, in 
    print (min( 4,12,43.3,19,"GeeksforGeeks" ) )
TypeError:unorderable types:str() < int()

实际应用

在许多字典中,实际应用之一是找到按字典顺序排列的最大和最小的字符串,即在字典中排在最前或最后的字符串。

# Python code to demonstrate the Application of  
# min() and max() 
  
# printing the word occurring 1st among these in dict. 
# "geeks", "manjeet", "algorithm", "programming" 
print("The word occurring 1st in dict. among given is:",end="") 
print (min( "geeks", "manjeet", "algorithm", "programming" ) ) 
  
# printing the word occurring last among these in dict. 
# "geeks", "manjeet", "algorithm", "programming" 
print("The word occurring last in dict. among given is:",end="") 
print (max( "geeks", "manjeet", "algorithm", "programming" ) )

输出:

The word occurring 1st in dict. among given is:algorithm
The word occurring last in dict. among given is:programming



相关用法

注:本文由纯净天空筛选整理自 max() and min() in Python。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。