您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python迭代器和生成器怎么实现
## 1. 迭代器基础概念
### 1.1 什么是迭代器
迭代器(Iterator)是Python中实现迭代协议的对象,它必须实现`__iter__()`和`__next__()`两个方法:
- `__iter__()`:返回迭代器对象本身
- `__next__()`:返回容器中的下一个元素
### 1.2 迭代器示例
```python
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
value = self.data[self.index]
self.index += 1
return value
# 使用示例
my_iter = MyIterator([1, 2, 3])
for item in my_iter:
print(item) # 输出:1 2 3
生成器是通过函数中包含yield
语句实现的特殊迭代器:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
# 使用示例
counter = count_up_to(5)
print(next(counter)) # 输出:1
print(next(counter)) # 输出:2
类似列表推导式,但使用圆括号:
gen_exp = (x**2 for x in range(5))
print(next(gen_exp)) # 输出:0
print(next(gen_exp)) # 输出:1
特性 | 迭代器 | 生成器 |
---|---|---|
实现方式 | 类实现__iter__ 和__next__ |
函数包含yield 语句 |
内存效率 | 较高 | 更高(按需生成值) |
代码复杂度 | 较高 | 较低 |
状态保持 | 手动维护 | 自动维护 |
def read_large_file(file_path):
with open(file_path) as f:
while True:
line = f.readline()
if not line:
break
yield line
# 逐行处理大文件而不耗尽内存
for line in read_large_file('huge_file.txt'):
process(line)
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print(next(fib)) # 0
print(next(fib)) # 1
print(next(fib)) # 1
def generator_with_send():
while True:
received = yield
print(f"Received: {received}")
gen = generator_with_send()
next(gen) # 启动生成器
gen.send("Hello") # 输出:Received: Hello
def chain_generators(*iterables):
for it in iterables:
yield from it
combined = chain_generators([1,2], (x for x in range(3,5)))
list(combined) # 结果:[1, 2, 3, 4]
itertools
模块中的工具函数def squares(n):
for i in range(n):
yield i**2
sq = squares(5)
list(sq) # [0, 1, 4, 9, 16]
list(sq) # [] (生成器已耗尽)
def safe_generator(data):
for item in data:
try:
yield process_item(item)
except Exception as e:
print(f"Error processing {item}: {e}")
continue
掌握迭代器和生成器能显著提升Python代码的质量和效率,特别是在处理流式数据或内存敏感场景时。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。