Python生成器是一种特殊的迭代器,它允许你在函数中使用yield
关键字返回一个序列的值,而不是像普通的函数那样使用return
。生成器的主要功能包括:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
def infinite_sequence():
i = 0
while True:
yield i
i += 1
squares = (x * x for x in range(10))
def read_file(file_path, block_size=1024):
with open(file_path, 'r') as file:
while True:
data = file.read(block_size)
if not data:
break
yield data
def filter_even_numbers(numbers):
for number in numbers:
if number % 2 == 0:
yield number
总之,Python生成器提供了一种高效、简洁的方法来处理大量数据和复杂迭代逻辑。