在 Python 中使用 min() 和 max()
在本文中,我們將學習 Python 標準庫中包含的 min 和 max 函式。它根據用法接受無限數量的引數
語法
max( arg1,arg2,arg3,...........)
返回值 - 所有引數中的最大值
錯誤和異常:此處僅在引數不屬於同一型別的情況下引發錯誤。比較時會遇到錯誤。
讓我們首先看看實現 max() 函式的所有方式。
示例
# Getting maximum element from a set of arguments passed
print("Maximum value among the arguments passed is:"+str(max(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Maximum value among the arguments passed is:"+str(max('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Maximum element of the list is:"+str(max(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Maximum element of the tuple is:"+str(max(l)))輸出
Maximum value among the arguments passed is:7 Maximum value among the arguments passed is:z Maximum element of the list is:45 Maximum element of the tuple is:91
在這裡清楚地看到,透過使用 max 函式,我們可以在沒有進行任何比較操作的情況下直接獲取引數中的最大值。
同樣,我們可以在此實現 min() 函式
示例
# Getting maximum element from a set of arguments passed
print("Minimum value among the arguments passed is:"+str(min(2,3,4,5,7,2,1,6)))
# the above statement also executes for characters as arguments
print("Minimum value among the arguments passed is:"+str(min('m','z','a','b','e')))
# it can also a accept arguments mapped in the form of a list
l=[22,45,1,7,3,2,9]
print("Minimum element of the list is:"+str(min(l)))
# it can also a accept arguments mapped in the form of a tuple
l=(22,45,1,7,71,91,3,2,9)
print("Minimum element of the tuple is:"+str(min(l)))輸出
Minimum value among the arguments passed is:1 Minimum value among the arguments passed is:a Minimum element of the list is:1 Minimum element of the tuple is:1
透過使用 max() 和 min() 等內建函式,我們可以在不實際實現進行比較的邏輯的情況下直接獲得相應的最大值和最小值
結論
在本文中,我們學習了標準 Python 庫中包含的 max 和 min 函式的實現。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP