LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 59. ジェネレーター

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■ジェネレーター

◆普通に記述した場合

l = ['Good morning', 'Good afternoon', 'Good night']

for i in l:
    print(i)
result
Good morning
Good afternoon
Good night

◆ジェネレーターを使って記述した場合

def greeting():
    yield 'Good morning'
    yield 'Good afternoon'
    yield 'Good night'

g = greeting()

print(next(g))
print(next(g))
print(next(g))
result
Good morning
Good afternoon
Good night

Pythonでは、 def 内に yield があると、そのfunctionはジェネレーターとして認識される。
next() を用いることで、要素を1つずつ処理することができる。

これだけではあまりメリットは感じないかもしれないが、次のコードを見てみよう。

def greeting():
    yield 'Good morning'
    yield 'Good afternoon'
    yield 'Good night'

g = greeting()

print(next(g))
print('run!')
print(next(g))
print('run!')
print(next(g))
result
Good morning
run!
Good afternoon
run!
Good night

forループを使って記述すると、最初から最後まで一気に処理が走ってしまう。
ジェネレーターを使うと、好きなタイミングで処理を一旦止めて、別の処理を走らせたりできる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0