yield【ジェネレータ関数・一時停止】

yield【ジェネレータ関数・一時停止】

メモ

構文

yield 戻り値 (複数:カンマ区切り) [,]
(yield 戻り値 (複数:カンマ区切り) [,])

yield from サブジェネレータ 3.3
(yield from サブジェネレータ) 3.3

def generator_1(x):
    for i in range(x):
        yield i * 3  # 0 -> 3 -> 6 -> 9 -> ...

print("__next__()")
gen = generator_1(4)
print(gen.__next__())
print(gen.__next__())
print(gen.__next__())
print(gen.__next__())

print("\nfor-in")
for i in generator_1(4):
    print(i)

print("\nnext()")
gen = generator_1(4)
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
【出力例】
__next__()
0
3
6
9

for-in
0
3
6
9

next()
0
3
6
9
def generator_send():
    i = 0
    while True:
        val = (yield i)
        if val is not None:
            i = val
        else:
            i += 1

gen_send = generator_send()
print(next(gen_send))
print(next(gen_send))
print(gen_send.send(5))
print(next(gen_send))
print(next(gen_send))
【出力例】
0
1
5
6
7
def generator_2(x, y):
    for i in range(y):
        yield i * x  # 0 -> x -> 2x -> 3x -> ...

def generator_from(g1, g2):
    print("yield from g1")
    yield from g1
    print("yield from g2")
    yield from g2

gen1 = generator_2(2, 4)  # 0 -> 2 -> 4 -> 6
gen2 = generator_2(3, 4)  # 0 -> 3 -> 6 -> 9
for g in generator_from(gen1, gen2):
    print(g)
【出力例】
yield from g1
0
2
4
6
yield from g2
0
3
6
9