ジェネレーターとは?どう作る?

Pythonでコーディング面接問題を練習する

Kirill Smirnov

Data Science Consultant, Altran

定義

「ジェネレーター」— 本体に yield を含む関数が作る特別なイテラブル。

def func():
    # とても複雑な計算の結果を返す
    return 0
result = func()
print(result)
0
Pythonでコーディング面接問題を練習する

定義

「ジェネレーター」— 本体に yield を含む関数が作る特別なイテラブル。

def func():
    # とても複雑な計算の結果を yield する
    yield 0
result = func()
print(result)
<generator object result at 0x105736e10>
Pythonでコーディング面接問題を練習する

イテラブルとしてのジェネレーター

def func():
    # とても複雑な計算の結果を yield する
    yield 0

result = func()
for item in result:
    print(item)
0
Pythonでコーディング面接問題を練習する

yield を増やす

def func():
    yield 0
    yield 1
    yield 2
result = func()
for item in result:
    print(item)
0
1
2
Pythonでコーディング面接問題を練習する

ループ内の yield

def func(n):
    for i in range(0, n):
        yield 2*i
result = func(3)
for item in result:
    print(item)
0
2
4
Pythonでコーディング面接問題を練習する

ジェネレーターをリストに変換

def func(n):
    for i in range(0, n):
        yield 2*i

result = func(5)
list(result)
[0, 2, 4, 6, 8]
Pythonでコーディング面接問題を練習する

イテレーターとしてのジェネレーター

ジェネレーターは Iterable かつ Iterator です

def func(n):
    for i in range(0, n):
        yield 2*i
result = func(3)
next(result)
0
next(result)
2
next(result)
4
next(result)
StopIteration
Pythonでコーディング面接問題を練習する

ジェネレーターは使い切り

def func(n):
    for i in range(0, n):
        yield 2*i
result = func(3)
for item in result:
    print(item)
0
2
4
for item in result:
    print(item)
# 出力なし
result = func(3)
for item in result:
    print(item)
0
2
4
Pythonでコーディング面接問題を練習する

ジェネレーターは使い切り

def func(n):
    for i in range(0, n):
        yield 2*i
result = func(3)
list(result)
[0, 2, 4]
list(result)
[]
result = func(3)
list(result)
[0, 2, 4]
Pythonでコーディング面接問題を練習する

ジェネレーター内包表記

result = [2*i for i in range(0, 3)]
print(result)
[0, 2, 4]
result = (2*i for i in range(0, 3))
print(result)
<generator object result at 0x105736e10>
Pythonでコーディング面接問題を練習する

走査

result = (2*i for i in range(0, 3))
for item in result:
    print(item)
0
2
4
next(result)
StopIteration
Pythonでコーディング面接問題を練習する

なぜジェネレーター?

  • 独自のイテラブルを簡単に作成

[1, 3, 2, 4, 3, 5]

def create_jump_sequence(n):
    for i in range(1, n-1):
        yield i
        yield i+2
jump_sequence = create_jump_sequence(5)
list(jump_sequence)
[1, 3, 2, 4, 3, 5]
Pythonでコーディング面接問題を練習する

なぜジェネレーター?

  • 独自のイテラブルを簡単に作成
  • 遅延初期化(lazy)

[1, 3, 2, 4, 3, 5, 4, 6, 5, 7, ...]

def create_jump_sequence(n):
    for i in range(1, n-1):
        yield i
        yield i+2
jump_sequence = create_jump_sequence(500)
next(jump_sequence)
1
Pythonでコーディング面接問題を練習する

なぜジェネレーター?

  • 独自のイテラブルを簡単に作成
  • 遅延初期化(lazy)
  • 無限イテラブルも作成可能
def create_inf_generator():
    while True:
        yield 'I am infinite!'
inf_generator = create_inf_generator()
next(inf_generator)
I am infinite
Pythonでコーディング面接問題を練習する

Let's practice!

Pythonでコーディング面接問題を練習する

Preparing Video For Download...