當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。