Python min() 函式



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

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

語法

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

min(x, y, z, ....)

引數

  • x, y, z - 這是一個數字表達式。

返回值

此函式返回其引數中最小的一個。

示例

以下示例演示了 Python min() 函式的用法。在這裡,我們檢索傳遞給函式的引數中最小的數字。

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

執行以上程式時,會產生以下結果:

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

示例

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

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

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

The smallest number in the list is:  2

示例

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

# Creating the string
Str = ['dog','cat','kit']
small = min(Str)
print("The minimum of the strings is: ", small)

以上程式碼的輸出如下:

The minimum of the strings is:  cat

示例

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

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

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

The smallest key value is:  Animal
python_built_in_functions.htm
廣告