ZetCode

Python max 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨了 Python 的 max 函数,它返回可迭代对象中的最大项或参数中的最大值。我们将介绍数字、字符串、自定义对象和实际示例。

基本定义

max 函数从可迭代对象或两个或多个参数中返回最大项。 它可以接受用于自定义比较的键函数和用于空可迭代对象的默认值。

主要特征:适用于任何可比较的类型(数字、字符串等),接受可选的键函数,并为没有默认值的空可迭代对象引发 ValueError。

基本数字用法

这是一个使用不同数字类型的简单用法,展示了 max 如何找到数字之间的最大值。

basic_max.py
# With multiple arguments
print(max(10, 20, 30))    # 30

# With an iterable
numbers = [5, 2, 8, 4, 1]
print(max(numbers))       # 8

# With mixed numeric types
print(max(3.14, 2, 5.6))  # 5.6

此示例显示了具有不同数字输入的 max。 它适用于单独的参数和可迭代对象。 Python 自动处理混合数字类型。

该函数使用标准比较规则比较值,因此可以直接比较整数和浮点数。

字符串比较

max 函数还可以比较字符串,根据 Unicode 代码点查找字典序上最大的字符串。

string_max.py
words = ["apple", "banana", "cherry"]
print(max(words))  # 'cherry'

# Based on Unicode values
chars = ['a', 'A', 'z', 'Z']
print(max(chars))  # 'z'

# With key function for case-insensitive comparison
print(max(words, key=lambda x: x.lower()))  # 'cherry'

默认情况下,字符串比较区分大小写,大写字母的 Unicode 值低于小写字母。 键函数允许自定义比较逻辑。

该示例展示了如何通过在比较期间将字符串转换为小写来执行不区分大小写的比较。

具有键函数的自定义对象

键函数参数允许根据自定义标准查找最大值。 此示例查找列表中最长的单词。

key_function.py
words = ["cat", "elephant", "mouse", "giraffe"]

# Find longest word by length
longest = max(words, key=lambda x: len(x))
print(longest)  # 'elephant'

# Find word with highest ASCII sum
max_ascii = max(words, key=lambda x: sum(ord(c) for c in x))
print(max_ascii)  # 'elephant'

第一个示例使用 len 作为键查找最长的单词。 第二个示例计算单词中每个字符的 ASCII 值之和。

键函数允许灵活的比较,而无需修改原始数据或创建自定义比较方法。

具有 __gt__ 的自定义对象

您可以通过实现 __gt__ 特殊方法使自定义对象与 max 一起使用。 此示例创建一个 Person 类。

custom_max.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __gt__(self, other):
        return self.age > other.age
    
    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

people = [
    Person("Alice", 25),
    Person("Bob", 30),
    Person("Charlie", 20)
]

print(max(people))  # Person('Bob', 30)

Person 类实现 __gt__ 以按年龄进行比较。 当我们对 Person 实例列表调用 max 时,Python 会使用此方法。

当您希望对象具有用于比较操作的自然顺序时,此模式非常有用。

处理空可迭代对象

当与空可迭代对象一起使用时,max 函数会引发 ValueError。 此示例展示了正确的错误处理。

empty_iterables.py
empty_list = []

# Without default (raises error)
try:
    print(max(empty_list))
except ValueError as e:
    print(f"Error: {e}")  # max() arg is an empty sequence

# With default value
print(max(empty_list, default="No items"))  # 'No items'

# With default None
print(max(empty_list, default=None))  # None

这些示例演示了 max 在空序列中的行为。 提供默认值可防止空可迭代对象的 ValueError。

当处理可能为空的数据(例如数据库查询结果)时,default 参数特别有用。

性能注意事项

此示例比较了 max 性能与查找最大值的替代方法。

performance.py
import timeit
import random

numbers = [random.randint(1, 1000) for _ in range(10000)]

def test_max():
    return max(numbers)

def test_sorted():
    return sorted(numbers)[-1]

def test_loop():
    m = numbers[0]
    for n in numbers[1:]:
        if n > m:
            m = n
    return m

print("max():", timeit.timeit(test_max, number=1000))
print("sorted():", timeit.timeit(test_sorted, number=1000))
print("Loop:", timeit.timeit(test_loop, number=1000))

这会评估不同的最大值查找方法。 max 通常是最快的,因为它针对此特定操作进行了优化。

排序方法慢得多,因为它对整个列表进行排序。 手动循环更接近,但不如 max 可读。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。 我自 2007 年以来一直在撰写编程文章。到目前为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程