Python 內建 max() 函式用於回傳可迭代物件中的最大值,或多個引數中的最大值。支援數字、字串、元組等可比較型別,並提供 key 參數實現自訂比較邏輯。
print(max(1, 5, 3, 9, 2)) # 9
print(max('a', 'z', 'c')) # 'z' (字典序)
print(max(3.14, 2.71, 1.41)) # 3.14
numbers = [10, 5, 8, 20, 3]
print(max(numbers)) # 20
print(max((1, 5, 3))) # 5
print(max({2, 8, 4})) # 8
# 字串視為字元序列
print(max("hello")) # 'o' (ASCII 碼最大)
key 接受單引數函式,將每個元素轉換為比較用的鍵值,原元素不變:
words = ['apple', 'banana', 'cherry', 'date']
print(max(words, key=len)) # 'banana' (長度 6)
print(max(words, key=lambda s: s[-1])) # 'date' (按最後一字元比較)
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return f"Student({self.name}, {self.score})"
students = [
Student("Alice", 85),
Student("Bob", 92),
Student("Charlie", 78)
]
top_student = max(students, key=lambda s: s.score)
print(top_student) # Student(Bob, 92)
# 使用 operator.attrgetter 更簡潔高效
from operator import attrgetter
print(max(students, key=attrgetter('score')))
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
print(max(scores, key=scores.get)) # 'Bob' (回傳鍵)
print(max(scores.values())) # 92 (回傳值)
print(max(scores.items(), key=lambda kv: kv[1])) # ('Bob', 92)
Python 3.4+ 支援 default 避免 ValueError:
empty_list = []
print(max(empty_list, default=None)) # None
print(max(empty_list, default=float('-inf'))) # -inf
students = [
("Alice", 85),
("Bob", 92),
("Charlie", 85),
("David", 92)
]
# 分數降序、名字升序
print(max(students, key=lambda x: (x[1], -ord(x[0][0]))))
# 實務建議用 sorted 取前 N
top3 = sorted(students, key=lambda x: (-x[1], x[0]))[:3]
import os
files = ['a.txt', 'b.log', 'c.py']
largest = max(files, key=os.path.getsize)
print(f"最大檔案: {largest} ({os.path.getsize(largest)} bytes)")
from datetime import datetime
dates = [
datetime(2023, 1, 15),
datetime(2023, 3, 22),
datetime(2022, 12, 31)
]
print(max(dates)) # 2023-03-22 00:00:00
min() 參數完全相同,回傳最小值:
print(min([5, 2, 8], key=lambda x: -x)) # 8 (按負值比較,相當於 max)
| 場景 | 建議做法 | 時間複雜度 |
|---|---|---|
| 單次找最大值 | max(iterable) | O(n) |
| 需前 N 大 | heapq.nlargest(n, iterable) | O(n log k) |
| 頻繁插入/查詢最大 | heapq (最大堆用負值) | O(log n) |
| 已排序序列 | 直接取 [-1] | O(1) |
import heapq
import random
data = [random.randint(1, 1000) for _ in range(10000)]
# 找前 5 大
top5 = heapq.nlargest(5, data)
print(top5)
# 針對複雜物件
top3_students = heapq.nlargest(3, students, key=lambda s: s.score)
default 或預先檢查__lt__ 等豐富比較方法key=dict.getmax() 在 C 層面實作為 builtin_max(),核心邏輯:
key 函式:每次比較前呼叫,結果快取避免重複計算原始碼位置:Python/bltinmodule.c
max() 是 Python 最實用的內建函式之一,搭配 key 參數能優雅解決各種「依特定條件找最大」問題。掌握 key、default、operator 模組輔助函式,以及何時改用 heapq,能寫出更簡潔、高效、Pythonic 的程式碼。記住:找單一最大值用 max,找前 N 大用 heapq.nlargest。