Python min() 函数详解
min() 是 Python 的核心内置函数,用于返回可迭代对象中的最小值或多个参数中的最小值,支持自定义比较规则。
核心功能与语法
基础用法
从序列中取最小值
min([3, 1, 4, 2]) 返回 1
多参数直接比较
min(5, 2, 9) 返回 2
高级用法
-
自定义比较规则(
key参数)words = ["apple", "zebra", "elephant"] min(words, key=len) 返回 "apple"(最短单词) -
空序列处理(
default参数)min([], default="EMPTY") 返回 "EMPTY" -
字典操作
scores = {"Alice": 85, "Bob": 92, "Charlie": 78} min(scores) 返回 "Alice"(键的最小值) min(scores, key=scores.get) 返回 "Charlie"(值的最小值)
关键特性
| 特性 | 说明 | 示例 |
|---|---|---|
| 多类型支持 | 支持数字、字符串等可比较类型 |
min(3.14, 2.71) → 2.71
|
| 字典键比较 | 默认比较字典的键 |
min({"b":1, "a":2}) → 'a'
|
| 稳定性 | 多个最小值时返回第一个 |
min([(1,'a'), (1,'b')]) → (1,'a')
|
| 空值保护 | 无default时空序列触发ValueError
|
min([]) → ❌ 错误 |
底层原理
-
比较机制:
- 调用对象的
__lt__()方法进行比较 - 自定义类需实现比较方法:
class Product: def __init__(self, price): self.price = price def __lt__(self, other): return self.price < other.price min(Product(10), Product(5)) 返回价格5的产品
- 调用对象的
-
时间复杂度:
- 单次遍历:O(n) 线性复杂度
- 比
sorted(iterable)[0]更高效(避免全排序)
典型应用场景
-
数据分析
获取数据集中最小值 temperatures = [22.5, 19.8, 25.3, 18.1] min_temp = min(temperatures) -
文件处理
查找最短行 with open("log.txt") as f: shortest = min(f, key=len, default="No lines") -
自定义对象处理
class Student: def __init__(self, name, score): self.name = name self.score = score students = [Student("Alice", 88), Student("Bob", 92)] min_student = min(students, key=lambda s: s.score)
⚠️ 注意:
- 混合类型(如数字和字符串)比较会触发
TypeError- 大文件处理建议使用生成器而非列表(节省内存)