- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
自 python 2.5 以来,可以将 send()
、throw()
、close()
放入生成器中。在定义的生成器中,可以通过执行以下操作来“捕获”发送的数据:
def gen():
while True:
x = (yield)
if x == 3:
print('received 3!!')
break
else:
yield x
我想玩的是做类似的事情:
def gen2():
while True:
yield (yield)
注意到它是一个合法的生成器,可以做一些事情..我想弄清楚的第一件事是:
这样写有什么好的用法吗?
同样在做类似的事情时:
g = gen2()
next(g)
g.send(10) # output: 10
g.send(2) # output: nothing
g.send(3) # output: 3
g.send(44) # output: nothing
为什么每秒“发送”都没有做任何事情?
最佳答案
yield (yield)
首先从内部 yield
产生 None
。然后它从 send
或 next
接收一个值。内部 yield
评估这个接收到的值,而外部 yield
立即产生该值。
每个 yield
在概念上都包含两个部分:
send
或next
的调用者传递一个值。send
或 next
调用接收值。同样,每个send
或next
在概念上都有两部分:
yield
表达式。 (对于 next
,此值为 None
。)yield
表达式接收一个值。系统中最令人困惑的部分可能是这些部分是交错的。 yield
的两部分对应于 send
或 next
的两个不同调用,send
的两部分> 或 next
对应于两个不同的 yield
。
如果我们研究一个简单的例子:
def gen():
print('Not ran at first')
yield (yield)
g = gen() # Step 1
print(next(g)) # Step 2
print(g.send(1)) # Step 3
g.send(2) # Step 4
事情是这样的:
Inside the generator Outside the generator
第一步
g calls gen()
g returns a generator object
without executing the print
just yet statement.
>>> g
<generator object gen at 0x7efe286d54f8>
第 2 步
next(g) sends None to g
g receives None, ignores it
(since it is paused at the start
of the function)
g prints ('not ran at first')
g executes the "transmit" phase
of the inner yield, transmitting
None
next(g) receives None
第 3 步
g.send(1) sends 1 to g
g executes the "receive" phase
of the inner yield, receiving 1
g executes the "transmit" phase
of the outer yield, transmitting 1
g.send(1) receives 1 from g
第四步
g.send(2) sends 2 to g
g executes the "receive" phase
of the outer yield, receiving 2
g reaches the end of gen and raises
a StopIteration
g.send(2) raises the StopIteration
from g
关于python - yield (yield) 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899681/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!