內置函數min()
有助於返回給定 iterable 中的最小元素。也可以在兩個或多個參數之間找到最小的元素。
# to find the smallest item in an iterable
**min(iterable, *iterables, key, default)**
# to find the smallest item between two or more objects
**min(arg1, arg2, *args, key)**
最小()參數:
帶有 iterable 的min()
函數具有以下參數。
*分鐘(可重複,可重複,鍵,默認)**
參數 | 描述 | 必需/可選 |
---|---|---|
可迭代的 | 諸如列表、元組、集合、字典等可條目。 | 需要 |
*可重複 | 任意數量的可滴定物;可以不止一個 | 可選擇的 |
鍵 | 傳遞數據項並進行比較的一種關鍵功能 | 可選擇的 |
系統默認值 | 如果給定的 iterable 為空,則為默認值 | 可選擇的 |
不帶iterable()
的iterable()
函數有以下參數。
【t0 min(arg1、arg2、*args、鍵)】的縮寫
參數 | 描述 | 必需/可選 |
---|---|---|
arg1 | 一個對象;可以是數字、字元串等 | 需要 |
arg2 | 一個對象;可以是數字、字元串等 | 需要 |
*參數 | 任意數量的對象 | 可選擇的 |
鍵 | 傳遞每個參數並進行比較的一個關鍵函數 | 可選擇的 |
最小()返回值
在傳遞空迭代器的情況下,它會引發 ValueError 異常。為了避免這種情況,我們可以傳遞默認參數。
如果我們傳遞多個迭代器,那麼從給定的迭代器中返回最小的項。
| 投入 | 返回值 |
| 整數 | 最小整數 |
| 線 | 具有最小 Unicode 值的字元 |
Python 中min()
方法的示例
示例 1:獲取列表中最小的項目
number = [13, 2, 8, 25, 10, 46]
smallest_number = min(number);
print("The smallest number is:", smallest_number)
Output
輸出:
The smallest number is: 2
示例 2:列表中最小的字元串
languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);
print("The smallest string is:", smallest_string)
輸出:
The smallest string is: C Programming
示例 3:在字典中查找min()
square = {2: 4, 3: 9, -1: 1, -2: 4}
# the smallest key
key1 = min(square)
print("The smallest key:", key1) # -2
# the key whose value is the smallest
key2 = min(square, key = lambda k: square[k])
print("The key with the smallest value:", key2) # -1
# getting the smallest value
print("The smallest value:", square[key2]) # 1
輸出:
TThe smallest key: -2
The key with the smallest value: -1
The smallest value: 1
例 4:在給定的數字中找出最小值
result = min(4, -5, 23, 5)
print("The minimum number is:", result)
輸出:
The minimum number is -5
示例 5:查找對象的最小值()
class Data:
id = 0
def __init__(self, i):
self.id = i
def __str__(self):
return 'Data[%s]' % self.id
def get_data_id(data):
return data.id
# min() with objects and key argument
list_objects = [Data(1), Data(2), Data(-10)]
print(min(list_objects, key=get_data_id))
輸出:
Data[-10]
原創文章,作者:IZ178,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129656.html