iter() 是 Python 的内置函数,用于创建迭代器对象,支持两种调用方式:
- 基础用法:从可迭代对象创建迭代器
my_list = [1, 2, 3]
it = iter(my_list) 创建列表迭代器
print(next(it)) 输出: 1
print(next(it)) 输出: 2
- 高级用法:带哨兵值的迭代器
持续调用函数直到返回指定哨兵值
count = 0
def counter():
global count
count += 1
return count
it = iter(counter, 5) 当函数返回5时停止迭代
for num in it:
print(num) 输出: 1, 2, 3, 4
核心机制
-
对象要求:
- 单参数:对象需实现
__iter__()方法(如列表、元组、字典) - 双参数:第一个参数必须是可调用对象(函数或方法)
- 单参数:对象需实现
-
迭代协议:
class MyRange: def __init__(self, n): self.n = n self.i = 0 def __iter__(self): return self def __next__(self): if self.i < self.n: i = self.i self.i += 1 return i raise StopIteration for num in MyRange(3): 输出: 0, 1, 2 print(num)
典型场景
- 文件逐行读取:
with open("data.txt") as f: for line in iter(f.readline, ""): 遇到空行停止 process(line) - 自定义数据流处理
- 内存高效的大数据遍历
⚠️ 注意:迭代器为一次性对象,耗尽后需重新创建。