内置函数 max() 用于返回给定可迭代对象中的最大元素。它也可以用于查找两个或多个参数中的最大元素。
# 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)
带有可迭代对象的 max() 函数有以下参数。
max(iterable, *iterables, key, default)
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 可迭代对象 | 一个可迭代对象,例如列表、元组、集合、字典等。 | 必需 |
| *iterables | 任意数量的可迭代对象;可以多于一个。 | 可选 |
| 键 | 一个 key 函数,可迭代对象会被传递给它并进行比较。 | 可选 |
| 默认值 | 如果给定可迭代对象为空,则为默认值。 | 可选 |
不带可迭代对象的 max() 函数有以下参数。
max(arg1, arg2, *args, key)
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| arg1 | 一个对象;可以是数字、字符串等。 | 必需 |
| arg2 | 一个对象;可以是数字、字符串等。 | 必需 |
| *args | 任意数量的对象。 | 可选 |
| key | 一个 key 函数,每个参数都会被传递给它并进行比较。 | 可选 |
如果传入空迭代器,它会引发 ValueError 异常,为了避免这种情况,我们可以传入 default 参数。
如果传入多个迭代器,则返回给定迭代器中最大的项。
| 输入 | 返回值 |
|---|---|
| 整型 | 最大的整数 |
| 字符串 | 具有最大 Unicode 值的字符 |
number = [13, 2, 8, 5, 10, 26]
largest_number = max(number);
print("The largest number is:", largest_number)
输出
The largest number is: 26
languages = ["Python", "C Programming", "Java", "JavaScript"]
largest_string = max(languages);
print("The largest string is:", largest_string)
输出
The largest string is: Python
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
result = max(4, -5, 23, 5)
print("The maximum number is:", result)
输出
The maximum number is: 23
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]