ジェネレーターの実用的応用:実世界でのユースケース
メニューを表示するにはスワイプしてください
ジェネレーターは、コンテキストマネージャとしてリソースを効率的に管理するために使用可能。たとえば、データベース接続、ファイル操作、ロック機構など。contextlibモジュールを利用することで、ジェネレーターはリソースの割り当てとクリーンアップをシームレスに処理。
1234567891011121314from contextlib import contextmanager @contextmanager def database_connection(): print("Opening database connection") connection = "Database Connection" # Simulated connection try: yield connection finally: print("Closing database connection") # Using the generator as a context manager with database_connection() as conn: print(f"Using {conn}")
大規模データの効率的な処理
ジェネレーターは、大規模なデータセットを遅延処理するデータパイプラインの構築に最適。パイプラインの各段階をジェネレーターとして実装することで、効率的かつメモリ効率の高い処理が可能。
12345678910111213141516171819202122232425262728293031323334353637383940import re # Stage 1: Read lines lazily def read_lines(text): for line in text.split("\n"): yield line # Stage 2: Filter non-empty lines def filter_lines(lines): for line in lines: if line.strip(): yield line # Stage 3: Extract words lazily def extract_words(lines): for line in lines: for word in re.findall(r'\w+', line): yield word # Stage 4: Transform words to lowercase def lowercase_words(words): for word in words: yield word.lower() # Input text text = """Generators are powerful tools They allow efficient data processing This pipeline demonstrates their usage""" # Build the pipeline lines = read_lines(text) filtered = filter_lines(lines) words = extract_words(filtered) lowercased = lowercase_words(words) # Process the data print("Processed words:") for word in lowercased: print(word)
1. ジェネレーター関数が yield する値がなくなった場合、何が起こりますか?
2. 次のコードは何を出力しますか?
3. 次のコードは何をしますか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 6. 章 5
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 6. 章 5