程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Learn the min() function in Python

編輯:Python

Python min() Function is another useful function,用於在你的 Python Process digital data in the program.min() A function can accept a sequence as its input,也可以接受兩個或多個項目的系列作為輸入.如果你向 min() The function is passed a sequence,It returns the smallest item in the sequence.If you pass two or more items,min()The function will return the smallest item of the items you pass.Let's see how to use it now Python min() Some examples of functions.


Python min() 函數示例 1

The first thing we can do is initialize a sequence,以便測試 min() 函數.在本例中,它是一個整數 12, -3, 17, -5, 99, 和 0 的列表.

現在我們可以調用 min() 函數並傳入 list_of_nums 變量,See what the smallest integer is,在本例中是 -5.


Python min() 函數示例 2

在使用 min() 函數時,同樣的方法也可以用在 Tuple 上.在第二個例子中,We initialize the sequence again,make it contain the same sequence of numbers.

再次使用 min() 函數,現在在 Tuple 上,產生同樣的結果,-5 是最小的數字.


Python min() 函數示例 3

Now we can test on some floating point numbers min() 函數.同樣,We start with an include1.8、-26.13、-9.53、105.8和-6.123These values ​​are tested on a list of floating point numbers.

當min()when applied to this list of floats,我們發現-26.13是最小的值.


Python min() 函數示例 4

在這個例子中,We just pass in a series of numbers,就可以看到min()函數的結果.


Python min() 函數示例 5

min()函數也可以和Pythonused together with a dictionary.when you use it on a dictionary min() 時,It looks at the key to determine the smallest value.

在上面的片段中,The keys of the dictionary use integer values.The next code snippet does the opposite,使用字符串作為鍵,整數作為值.We are here again dictionary 上調用 min() ,'a' 是最小的值.


設置一個默認值

如果你向 min() The function is passed an empty iterator,你會得到一個ValueError 的錯誤*:min() arg is an empty sequence*.

You can handle this situation by providing a default value.這樣一來,如果沒有最小值,就會返回默認值.


Use a custom key

你可以在min()Use a custom key in the function.If you want to find the minimum length of a string,而不是基於a到zThe minimum value of the string,你可以使用這個方法.


Python min() 函數總結

Python min() The function returns the item with the lowest value,Or the item with the lowest value in an iterable of items.如果值是字符串,Comparisons are made in alphabetical order,然而,We saw a way to change this by using custom keys. min() Accepts one or more items to compare,Or an iterable with one or more items to compare.We also saw how to set a default value,in case an empty iterable is passed in the function.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved