python3: yield from

python3: yield from

Python 3: Using "yield from" in Generators - Part 1html

yield from 後面跟一個generator。python

def generator2():
    for i in range(4):
        yield i

def generator3():
    for j in range(4, 8):
        yield j

def generator():
    for i in generator2():
        yield i
    for j in generator3():
        yield j

for i in generator():
    print(i)

運行結果以下:post

$ python3 test.py 
0
1
2
3
4
5
6
7

能夠用yield from簡化代碼:code

def generator2():
    for i in range(4):
        yield i

def generator3():
    for j in range(4, 8):
        yield j

def generator():
    yield from generator2()
    yield from generator3()

for i in generator():
    print(i)
相關文章
相關標籤/搜索