我试图通过coroutines
运算符来理解python中的yield
。
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
的理解,yeild
在生成器对象上使用next()
时返回下一个值。
答案 0 :(得分: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