您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。