實現 __iter__() 返回自身、__next__() 返回下一個元素或拋出 StopIteration 的對象即為迭代器。Python for 循環本質是:
iterator = iter(iterable)
while True:
try:
item = next(iterator)
# 循環體
except StopIteration:
break
迭代器按需產出元素,不預先計算整個序列,適合:
iter() 與 next()lst = [1, 2, 3]
it = iter(lst)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
next(it) # 拋出 StopIteration
enumerate() 獲取索引for idx, val in enumerate(['a', 'b', 'c']):
print(idx, val)
# 0 a
# 1 b
# 2 c
| 語法 | 類型 | 特點 |
|---|---|---|
(x for x in lst) | 生成器表達式 | 返回迭代器,惰性計算,內存高效 |
[x for x in lst] | 列表推導式 | 立即構建列表,佔用內存 |
原則:除非確需列表(如多次遍歷、索引訪問),優先使用生成器表達式。
# 條件篩選
(x*2 for x in lst if x > 0)
# 嵌套循環(順序即嵌套順序)
((x, y) for x in range(3) for y in range(x))
# 等價於
for x in range(3):
for y in range(x):
yield (x, y)
# 避免重複計算:嵌套生成器
# 糟糕:x.doSomething() 計算兩次
# 好:先計算存入中間生成器
tmp = (x.doSomething() for x in lst)
result = (x for x in tmp if x > 0)
標準庫 itertools 提供創建、組合、過濾迭代器的高性能 C 實現工具函數。
count(start=0, step=1) # 0,1,2,3... 或 10,12,14...
cycle('ABCD') # A,B,C,D,A,B,C,D...
repeat(elem, n=3) # elem, elem, elem (n次或無限)
chain('ABC', 'DEF') # A,B,C,D,E,F
compress(data, selectors) # 根據布爾選擇器篩選
dropwhile(pred, seq) # 跳過前綴滿足條件的元素
takewhile(pred, seq) # 取前綴滿足條件的元素
islice(iter, start, stop, step) # 迭代器切片
product('AB', repeat=2) # 笛卡爾積: AA, AB, BA, BB
permutations('ABCD', 2) # 排列: AB, AC, AD, BA...
combinations('ABCD', 2) # 組合: AB, AC, AD, BC...
groupby(sorted_data, key) # 連續相同鍵分組 (需預排序)
from itertools import islice
def batch_iter(iterator, batch_size):
"""將迭代器分批,每批為列表"""
while True:
batch = list(islice(iterator, batch_size))
if not batch:
break
yield batch
# 使用:逐行讀取大文件,每 1000 行處理一次
with open('huge.log') as f:
for batch in batch_iter(f, 1000):
process_batch(batch)
for 是其語法糖。itertools 以 C 級性能解決複雜迭代組合問題,熟悉常用函數可大幅簡化代碼。