Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ ジェネレーターの実用的応用:実世界でのユースケース | Pythonにおけるイテレータとジェネレータの習得
Python構造化プログラミング

bookジェネレーターの実用的応用:実世界でのユースケース

メニューを表示するにはスワイプしてください

ジェネレーターは、コンテキストマネージャとしてリソースを効率的に管理するために使用可能。たとえば、データベース接続ファイル操作ロック機構など。contextlibモジュールを利用することで、ジェネレーターはリソースの割り当てとクリーンアップをシームレスに処理。

1234567891011121314
from 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}")
copy

大規模データの効率的な処理

ジェネレーターは、大規模なデータセットを遅延処理するデータパイプラインの構築に最適。パイプラインの各段階をジェネレーターとして実装することで、効率的かつメモリ効率の高い処理が可能。

12345678910111213141516171819202122232425262728293031323334353637383940
import 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)
copy

1. ジェネレーター関数が yield する値がなくなった場合、何が起こりますか?

2. 次のコードは何を出力しますか?

3. 次のコードは何をしますか?

question mark

ジェネレーター関数が yield する値がなくなった場合、何が起こりますか?

正しい答えを選んでください

question mark

次のコードは何を出力しますか?

正しい答えを選んでください

question mark

次のコードは何をしますか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 6.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 6.  5
some-alt