[英]coroutines in python using yield
I am trying to understand coroutines
in python with yield
operator. 我试图用
yield
操作符理解python中的coroutines
。
def minimize():
current = yield
while True:
value = yield current
current = min(value, current)
I have the function minimize()
which returns the minimum value of the all the values that has been sent to the function till that point. 我有函数minimum
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
I have a question regarding the function. 我对功能有疑问。
what does current = yeild
achieve. current = yeild
目标是什么。 From what I understood of yield
in a generator context, yeild
returns the next value when you use next()
on the generator object. 根据我对生成器上下文中的
yield
理解,当在生成器对象上使用next()
时, yeild
返回下一个值。
Let's follow the flow control, indented items are the minimize()
generator: 让我们跟随流控制,缩进的项是
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.