Python迭代器与生成器

在这里插入图片描述

Python迭代器与生成器

1. 迭代器(Iterator)

基本概念

  • 迭代器是实现了迭代协议的对象,必须包含__iter__()__next__()方法
  • 迭代器是惰性计算的,只在需要时产生下一个值

创建迭代器

class MyIterator:
    def __init__(self, max_num):
        self.max_num = max_num
        self.current = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current < self.max_num:
            num = self.current
            self.current += 1
            return num
        else:
            raise StopIteration

# 使用迭代器
my_iter = MyIterator(5)
for num in my_iter:
    print(num)  # 输出: 0 1 2 3 4

内置迭代工具

  • iter(): 获取对象的迭代器
  • next(): 获取迭代器的下一个值

2. 生成器(Generator)

基本概念

  • 生成器是一种特殊的迭代器,使用yield关键字
  • 生成器函数在调用时返回一个生成器对象,而不是立即执行

创建生成器

# 生成器函数
def count_up_to(max_num):
    count = 0
    while count < max_num:
        yield count
        count += 1

# 使用生成器
counter = count_up_to(5)
for num in counter:
    print(num)  # 输出: 0 1 2 3 4

# 生成器表达式
gen_exp = (x**2 for x in range(5))
print(list(gen_exp))  # 输出: [0, 1, 4, 9, 16]

生成器特点

  1. 惰性求值:只在需要时产生值
  2. 内存高效:不需要预先生成所有值
  3. 只能迭代一次

3. 迭代器 vs 生成器

特性迭代器生成器
实现方式类实现__iter____next__函数使用yield关键字
代码复杂度较高较低
内存使用取决于实现总是高效
常见用途自定义复杂迭代逻辑简单迭代或大数据处理

4. 实际应用示例

读取大文件

def read_large_file(file_path):
    with open(file_path, 'r') as file:
        for line in file:
            yield line.strip()

# 使用生成器逐行处理大文件
for line in read_large_file('huge_file.txt'):
    process_line(line)  # 假设process_line是处理函数

无限序列

def infinite_sequence():
    num = 0
    while True:
        yield num
        num += 1

# 生成无限序列(使用时需要限制)
gen = infinite_sequence()
print(next(gen))  # 0
print(next(gen))  # 1
# 可以无限继续...

5. 高级特性

生成器双向通信

def generator_with_communication():
    received = yield "Ready"
    while received:
        received = yield f"Received: {received}"

gen = generator_with_communication()
print(next(gen))        # 输出: Ready
print(gen.send("Hello")) # 输出: Received: Hello
print(gen.send("World")) # 输出: Received: World

yield from语法(Python 3.3+)

def chain_generators(*iterables):
    for it in iterables:
        yield from it

result = list(chain_generators(range(3), 'abc'))
print(result)  # 输出: [0, 1, 2, 'a', 'b', 'c']

总结

  • 迭代器和生成器都是Python中处理序列的强大工具
  • 生成器提供了更简洁的实现方式,特别适合处理大数据流
  • 理解这些概念对于编写高效、Pythonic的代码至关重要
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aerkui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值