新聞中心
內(nèi)置函數(shù)max()有助于 返回給定可迭代表中最大的元素。也可以在兩個(gè)或多個(gè)參數(shù)之間找到最大的元素。

成都創(chuàng)新互聯(lián)是一家專業(yè)提供贛州企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、H5網(wǎng)站設(shè)計(jì)、小程序制作等業(yè)務(wù)。10年已為贛州眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站建設(shè)公司優(yōu)惠進(jìn)行中。
# to find the largest item in an iterable
**max(iterable, *iterables, key, default)**
# to find the largest item between two or more objects
**max(arg1, arg2, *args, key)**
最大()參數(shù):
帶有 iterable 的max()函數(shù)具有以下參數(shù)。
*最大值(可重復(fù),可重復(fù),鍵,默認(rèn))**
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 可迭代的 | 諸如列表、元組、集合、字典等可條目。 | 需要 |
| *可重復(fù) | 任意數(shù)量的可滴定物;可以不止一個(gè) | 可選擇的 |
| 鍵 | 傳遞數(shù)據(jù)項(xiàng)并進(jìn)行比較的一種關(guān)鍵功能 | 可選擇的 |
| 系統(tǒng)默認(rèn)值 | 如果給定的 iterable 為空,則為默認(rèn)值 | 可選擇的 |
不帶iterable()的iterable()函數(shù)有以下參數(shù)。
*最大值(arg1、arg2、args、鍵)**
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| arg1 | 一個(gè)對(duì)象;可以是數(shù)字、字符串等 | 需要 |
| arg2 | 一個(gè)對(duì)象;可以是數(shù)字、字符串等 | 需要 |
| *參數(shù) | 任意數(shù)量的對(duì)象 | 可選擇的 |
| 鍵 | 傳遞每個(gè)參數(shù)并進(jìn)行比較的一個(gè)關(guān)鍵函數(shù) | 可選擇的 |
最大()返回值
在傳遞空迭代器的情況下,它會(huì)引發(fā) ValueError 異常。為了避免這種情況,我們可以傳遞默認(rèn)參數(shù)。 如果我們傳遞多個(gè)迭代器,那么從給定的迭代器中返回最大的項(xiàng)。
| 投入 | 返回值 | | 整數(shù) | 最大整數(shù) | | 線 | 具有最大 Unicode 值的字符 |
Python 中max()方法的示例
示例 1:獲取列表中最大的項(xiàng)目
number = [13, 2, 8, 5, 10, 26]
largest_number = max(number);
print("The largest number is:", largest_number)
輸出:
The largest number is: 26示例 2:查找列表中最大的字符串
languages = ["Python", "C Programming", "Java", "JavaScript"]
largest_string = max(languages);
print("The largest string is:", largest_string)
輸出:
The largest string is: Python示例 3:在字典中查找max()
square = {2: 4, -3: 9, -1: 1, -2: 4}
# the largest key
key1 = max(square)
print("The largest key:", key1) # 2
# the key whose value is the largest
key2 = max(square, key = lambda k: square[k])
print("The key with the largest value:", key2) # -3
# getting the largest value
print("The largest value:", square[key2]) # 9
輸出:
The largest key: 2
The key with the largest value: -3
The largest value: 9例 4:在給定的數(shù)字中找出最大值
result = max(4, -5, 23, 5)
print("The maximum number is:", result)
輸出:
The maximum number is: 23示例 5:查找對(duì)象的最大值()
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
# max() with objects and key argument
list_objects = [Data(1), Data(2), Data(-10)]
print(max(list_objects, key=get_data_id))
輸出:
Data[2] 當(dāng)前名稱:創(chuàng)新互聯(lián)Python教程:Python max()
當(dāng)前網(wǎng)址:http://www.dlmjj.cn/article/cociiee.html


咨詢
建站咨詢
