2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonのyieldを習得

Last updated at Posted at 2021-08-16

pythonのyieldがわからない自分のためのメモ

要するにこう

def for_in_generator():
    for i in range(0, 10, 3):
        yield i

print([x for x in for_in_generator()]) # => [0, 3, 6, 9]

returnではなくyieldで値を返す。
返す度に止まります。
もう一度呼ばれると続きから。

generatorを理解するといいらしい

def my_generator():
    print('before yield')
    yield 1
    print('yielded 1')
    yield 2
    print('yielded 2')
    yield 3
    print('yielded 3, finished')

実行してみる

gen = my_generator()
print(type(gen))

v1 = gen.__next__()
print(type(v1))
print(v1)
v2 = gen.__next__()
v3 = gen.__next__()
v4 = gen.__next__()
<class 'generator'>
before yield
<class 'int'>
1
yielded 1
yielded 2
yielded 3, finished
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/tmp/ipykernel_101/3825958683.py in <module>
     17 v2 = gen.__next__()
     18 v3 = gen.__next__()
---> 19 v4 = gen.__next__()

StopIteration: 

__next__()で、最初のyield のが返ってくる。
genはそこで一時停止している状態。
__next__()をもう一度呼ぶと続きから次のyieldまでを実行。

現実的な使い方

for文にgeneratorを与えて、最後までgenerateしてあげること

for v in my_generator():
    print(v)
before yield
1
yielded 1
2
yielded 2
3
yielded 3, finished

リスト内包表記にも使う

print([v * 2 for v in my_generator()])  # => [2, 4, 6]
2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?