Python生成器在許多應用場景中都非常有用,因為它們允許你創建高效的迭代器,而不需要在內存中存儲整個數據集。以下是一些常見的應用場景:
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
import requests
def fetch_data(url):
response = requests.get(url)
for line in response.iter_lines():
yield line.decode('utf-8').strip()
def process_data_stream():
while True:
data = get_next_data_from_source() # 從數據源獲取數據的函數
if data is None:
break
yield process_data(data) # 處理數據的函數
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
import gzip
def read_compressed_file(file_path):
with gzip.open(file_path, 'rt') as file:
for line in file:
yield line.strip()
總之,Python生成器在處理大量數據、實時數據處理和內存優化等方面具有廣泛的應用場景。