Python生成器是一種特殊的迭代器,它允許你在函數(shù)中使用yield
關(guān)鍵字返回一個序列的值,而不是像普通的函數(shù)那樣使用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生成器提供了一種高效、簡潔的方法來處理大量數(shù)據(jù)和復(fù)雜迭代邏輯。