什麼是產生器,以及如何建立?

Python 程式面試題實作練習

Kirill Smirnov

Data Science Consultant, Altran

定義

Generator(產生器):在函式內使用 yield 關鍵字所建立的特殊可疊代物件。

def func():
    # Return a value from super complex calculations
    return 0
result = func()
print(result)
0
Python 程式面試題實作練習

定義

Generator(產生器):在函式內使用 yield 關鍵字所建立的特殊可疊代物件。

def func():
    # Yield a value from super complex calculations
    yield 0
result = func()
print(result)
<generator object result at 0x105736e10>
Python 程式面試題實作練習

產生器作為可疊代物件

def func():
    # Yield a value from super complex calculations
    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 程式面試題實作練習

將產生器轉成 list

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

result = func(5)
list(result)
[0, 2, 4, 6, 8]
Python 程式面試題實作練習

產生器作為 Iterator

Generator 既是 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)
# nothing
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 initialization)

[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 initialization)
  • 可以建立無限可疊代物件
def create_inf_generator():
    while True:
        yield 'I am infinite!'
inf_generator = create_inf_generator()
next(inf_generator)
I am infinite
Python 程式面試題實作練習

一起來練習吧!

Python 程式面試題實作練習

Preparing Video For Download...