Python 生成器协程
Python generator coroutine
试图更多地了解 python 中的 generator/send 函数。我在 link 中阅读了一些内容:generator send function purpose 帮助很大。
但我正在尝试理解下面的代码。为什么 next(checker)
是必要的?发送函数不会自动请求生成器中的下一项吗?我尝试在 for 循环之前只使用 next(checker)
,但它的功能不同。我认为发送函数将 'attempt' 作为 x 发送并产生是否 x == password
。我只是不明白为什么循环中有下一个(检查器)是必要的。
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
以上函数基于问题:
“为了验证你的功能,你想在本地测试它。给定一个尝试列表和正确的密码,return 第一次正确尝试的基于 1 的索引,或者 -1 如果有 none.
例子
对于attempts = ["hello", "world", "I", "like", "coding"]
和
password = "like"
,输出应该是
检查密码(尝试,密码)= 4."
Doesnt the send function automatically ask for the next item in the generator?
是的,但是这个生成器的编写方式,一半的值来自这个 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
ing 生成器将使用的值之前,总是必须有一个 next
(或等效的 send(None)
)。
试图更多地了解 python 中的 generator/send 函数。我在 link 中阅读了一些内容:generator send function purpose 帮助很大。
但我正在尝试理解下面的代码。为什么 next(checker)
是必要的?发送函数不会自动请求生成器中的下一项吗?我尝试在 for 循环之前只使用 next(checker)
,但它的功能不同。我认为发送函数将 'attempt' 作为 x 发送并产生是否 x == password
。我只是不明白为什么循环中有下一个(检查器)是必要的。
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
以上函数基于问题:
“为了验证你的功能,你想在本地测试它。给定一个尝试列表和正确的密码,return 第一次正确尝试的基于 1 的索引,或者 -1 如果有 none.
例子
对于attempts = ["hello", "world", "I", "like", "coding"]
和
password = "like"
,输出应该是
检查密码(尝试,密码)= 4."
Doesnt the send function automatically ask for the next item in the generator?
是的,但是这个生成器的编写方式,一半的值来自这个 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
ing 生成器将使用的值之前,总是必须有一个 next
(或等效的 send(None)
)。