2017-04-02 23 views
0

我想通過yield運算符來了解python中的coroutines在python中使用收益的協同程序

def minimize(): 
    current = yield 
    while True: 
     value = yield current 
     current = min(value, current) 

我有它返回所有已發送到功能,直到該點的值的最小值功能minimize()

it = minimize() 
next(it)   
print(it.send(10)) 
print(it.send(4)) 
print(it.send(22)) 
print(it.send(-1)) 

>>> 
10 
4 
4 
-1 

我有一個關於函數的問題。

current = yeild是做什麼的。根據我在生成器上下文中所瞭解的yield,當您在生成器對象上使用next()時,yeild會返回下一個值。

+1

'電流= yield'接收第一'it.send()'。然後運行到下一個'yield',它將產生10並等待下一個send() – AChampion

+0

@AChampion - 當你調用第二個'send'時,執行在'value = yield current'停止時確定'current = min(value,current)'得到執行。 – liv2hak

+1

第一個'send()'後,它正在'value = yield current'處等待。當你發送第二個值,value = 4時,current將成爲min(...),然後循環返回併產生4,並等待下一個send() 。 – AChampion

回答

2

讓我們跟隨的流量控制,縮進項是minimize()發生器:

it = minimize() # Creates generator 
next(it) 
    current = yield  # suspends on yield (implicit None) 
print(it.send(10)) 
    current = 10   # resumes 
    while True: 
     value = yield 10 # suspends on yield 
# Output: 10 
print(it.send(4)) 
     value = 4   # resumes 
     current = min(4, 10) 
    while True: 
     current = yield 4 
# Output: 4 
print(it.send(22)) 
     value = 22 
     current = min(22, 4) 
    while True: 
     current = yield 4 
# Output: 4 
print(it.send(-1)) 
     value = -1 
     current = min(-1, 4) 
    while True: 
     current = yield -1 
# Output: -1