[英]Python generator coroutine
試圖更多地了解python中的generator / send函數。 我在鏈接中讀到了一些內容: 生成器發送函數的目的很有幫助。
但是我試圖理解下面的代碼。 為什么next(checker)
必需的? 發送功能是否會自動要求生成器中的下一個項目? 我試着只是在for循環之前使用next(checker)
,但是功能不一樣。 我以為send函數將x嘗試發送為'attempt'並產生x == password
。 我只是不明白為什么需要在循環中使用next(checker)。
def checkPassword(attempts, password):
def check():
while True:
x = yield
yield x == password
checker = check()
for i, attempt in enumerate(attempts):
next(checker)
if checker.send(attempt):
return i + 1
return -1
上面的函數基於以下問題:
“為了驗證您的功能,您想在本地進行測試。給定嘗試列表和正確的密碼,請返回第一次正確嘗試的基於1的索引,如果沒有則返回-1。
例
對於attempts = ["hello", "world", "I", "like", "coding"]
和password = "like"
,輸出應為checkPassword(attempts,password)=4。“
發送功能是否會自動要求生成器中的下一個項目?
是的,但是生成器的編寫方式,一半的值來自此yield
:
x = yield
這只會產生None
。 對next
的調用消耗None
。
生成器的編寫方式可能有所不同,以消除大多數next
調用:
def checkPassword(attempts, password):
def check():
x = yield
while True:
x = yield x == password
checker = check()
next(checker)
for i, attempt in enumerate(attempts):
if checker.send(attempt):
return i + 1
return -1
但是,生成器與其用戶之間的yield
/ send
通信不能從send
開始,因為新的生成器在函數體的開始處停止,而不是在可以接收值的yield
處停止。 因此,在開始send
生成器將要使用的值之前,始終必須存在next
(或等效地為send(None)
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.