Python max() 函式



Python max() 函式用於從指定的可迭代物件中檢索最大元素。

查詢兩個給定數字中的最大值是我們通常執行的計算之一。通常,最大值是一個操作,我們在其中查詢給定值中的最大值。例如,從值“10、20、75、93”中,最大值為 93。

語法

以下是Python max() 函式的語法:

max(x, y, z, ....)

引數

  • x、y、z - 這是一個數值表示式。

返回值

此函式返回其引數中的最大值。

示例

以下示例顯示了 Python max() 函式的使用。在這裡,我們檢索傳遞給函式的引數中的最大數字。

print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))

當我們執行上述程式時,它會產生以下結果:

max(80, 100, 1000) :  1000
max(-20, 100, 400) :  400
max(-80, -20, -10) :  -10
max(0, 100, -400) :  100

示例

在這裡,我們建立一個列表。然後使用 max() 函式檢索列表的最大元素。

# Creating a list
List = [74,587,24,92,4,2,7,46]
res = max(List)
print("The largest number in the list is: ", res)

執行上述程式碼時,我們得到以下輸出:

The largest number in the list is:  587

示例

在下面的示例中,建立了一個等長字串列表。然後根據字母順序檢索最大字串

# Creating the string
Str = ['dog','cat','kit']
large = max(Str)
print("The maximum of the strings is: ", large)

上述程式碼的輸出如下:

The maximum of the strings is:  kit

示例

我們也可以在字典中使用 max() 函式來查詢最大的鍵,如下所示

# Creating the dictionary
dict_1 = {'Animal':'Lion', 'Kingdom':'Animalia', 'Order':'Carnivora'}
large = max(dict_1)
print("The largest key value is: ", large)

以下是上述程式碼的輸出:

The largest key value is:  Order
python_built_in_functions.htm
廣告