Python 迭代器与生成器详解
迭代器基础
迭代器是 Python 中用于顺序访问集合元素的对象,需实现__iter__
和__next__
方法。
class NumberIterator:
def __init__(self, limit):
self.limit = limit
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter < self.limit:
current = self.counter
self.counter += 1
return current
raise StopIteration
numbers = NumberIterator(3)
for num in numbers:
print(num)
生成器实现
生成器通过 yield 语句实现延迟计算,按需生成数据。
def fibonacci_generator(limit):
a, b = 0, 1
count = 0
while count < limit:
yield a
a, b = b, a + b
count += 1
fib = fibonacci_generator(5)
for number in fib:
print(number)
文件读取示例
生成器在处理大文件时特别有用。
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
def process_file(file_path):
for line in read_large_file(file_path):
processed_data = line.upper()
yield processed_data
无限序列生成
生成器可以创建无限序列,按需获取数据。
def infinite_counter():
num = 0
while True:
yield num
num += 1
counter = infinite_counter()
for _ in range(5):
print(next(counter))
生成器表达式
类似列表推导式的简洁语法创建生成器。
squares_gen = (x * x for x in range(5))
print(next(squares_gen))
print(next(squares_gen))
生成器进阶特性
send 方法允许向生成器发送值。
def number_generator():
while True:
received = yield
yield received * 2
gen = number_generator()
next(gen)
print(gen.send(10))
next(gen)
迭代器链式操作
通过迭代器实现数据处理管道。
def generate_numbers():
for i in range(5):
yield i
def square_numbers(numbers):
for num in numbers:
yield num * num
def filter_even(numbers):
for num in numbers:
if num % 2 == 0:
yield num
numbers = generate_numbers()
squared = square_numbers(numbers)
result = filter_even(squared)
for num in result:
print(num)