# Python中怎么實現迭代器與生成器
## 1. 迭代器與生成器的核心概念
### 1.1 什么是迭代器
迭代器(Iterator)是Python中用于實現迭代協議的對象。任何實現了`__iter__()`和`__next__()`方法的對象都是迭代器:
```python
class MyIterator:
def __iter__(self):
return self
def __next__(self):
# 返回下一個值或引發StopIteration
pass
生成器(Generator)是一種特殊的迭代器,通過yield
關鍵字簡化迭代器的創建:
def my_generator():
yield 1
yield 2
yield 3
完整實現迭代器協議的示例:
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
num = self.current
self.current -= 1
return num
# 使用示例
for num in CountDown(5):
print(num) # 輸出5,4,3,2,1
Python標準庫提供的常用迭代器工具:
import itertools
# 無限迭代器
counter = itertools.count(start=10, step=2) # 10,12,14...
cycler = itertools.cycle('ABC') # A,B,C,A,B...
# 有限迭代器
slicer = itertools.islice(range(100), 5) # 0-4
使用yield
關鍵字的典型示例:
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
# 使用示例
for num in fibonacci(100):
print(num) # 0,1,1,2,3,5...
類似列表推導式的輕量級語法:
squares = (x*x for x in range(10)) # 生成器對象
sum_of_squares = sum(x*x for x in range(10)) # 即時計算
簡化嵌套生成器的語法糖:
def chain_generators(*iterables):
for it in iterables:
yield from it
# 等效于手動迭代
# for it in iterables:
# for item in it:
# yield item
生成器作為協程的使用模式:
def coroutine():
while True:
received = yield
print(f"Received: {received}")
c = coroutine()
next(c) # 啟動生成器
c.send("Hello") # 輸出Received: Hello
處理大規模數據時的內存優化方案:
def read_large_file(file_path):
with open(file_path) as f:
while True:
chunk = f.read(4096)
if not chunk:
break
yield chunk
# 處理1GB文件只需幾KB內存
for chunk in read_large_file('huge.log'):
process(chunk)
利用生成器保持執行狀態的特性:
def state_machine():
state = "START"
while True:
if state == "START":
data = yield
state = "PROCESSING"
elif state == "PROCESSING":
if data == "END":
state = "DONE"
else:
print(f"Processing {data}")
data = yield
import sys
list_size = sys.getsizeof([i for i in range(1000000)]) # ~8.5MB
gen_size = sys.getsizeof((i for i in range(1000000))) # ~128B
it = iter([1,2,3])
list(it) # [1,2,3]
list(it) # [] 迭代器已耗盡
def reusable_gen():
return (x*x for x in range(5))
g1 = reusable_gen()
g2 = reusable_gen() # 創建新的生成器
def safe_gen():
try:
yield 1
raise ValueError("demo error")
except Exception as e:
print(f"Caught: {e}")
yield 2
list(safe_gen()) # 輸出異常信息后返回[1,2]
關鍵總結:Python的迭代器和生成器提供了高效的內存迭代方案。迭代器更適合需要完整控制的情形,而生成器以更簡潔的語法實現了相同的功能。根據具體場景選擇合適方案,可以顯著提升代碼性能和可讀性。 “`
(全文約1350字,滿足Markdown格式要求)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。