我无法弄清楚为什么我的生成器没有返回值= 11,这是我的代码:
def monG(borneinf,bornesup):
while True:
if bornesup < borneinf:
bornesup, borneinf = borneinf, bornesup
borneinf += 1
if borneinf==bornesup:
break
x=(yield borneinf)
if x is not None:
borneinf = x
c=monG(2,10)
for a in c:
if a==5:
c.send(20)
print(a)
输出:
3
4
5
12
13
14
15
16
17
18
19
答案 0 :(得分:2)
让我们更仔细地跟踪操作:
def monG(borneinf,bornesup):
while True:
if bornesup < borneinf:
bornesup, borneinf = borneinf, bornesup
borneinf += 1
if borneinf==bornesup:
break
print("TRACE", borneinf, bornesup)
x=(yield borneinf)
if x is not None:
borneinf = x
c = monG(2,10)
print(type(c))
for a in c:
if a==5:
print(c.send(20), "a==5")
print(a)
这为我们在c.send
行上添加了一个特殊标记,并为yield
前的窥视
输出:
<class 'generator'>
TRACE 3 10
3
TRACE 4 10
4
TRACE 5 10
TRACE 11 20
11 a==5
5
TRACE 12 20
12
TRACE 13 20
13
TRACE 14 20
14
TRACE 15 20
15
TRACE 16 20
16
TRACE 17 20
17
TRACE 18 20
18
TRACE 19 20
19
正如MisterMiyagi
所指出的,yield
确实返回11,但是您将其丢弃了。也许您想将该值分配给a
-尽管弄乱循环参数是明确的代码味道。如果进行分配,则在该迭代中打印出11
而不是5
。
我认为您的基本问题是,您干扰了迭代流程,从而在循环内施加了额外的yield
。在您编码的循环中,隐式yield
意味着您在连续的迭代中都不会同时获得 5
和11
。
答案 1 :(得分:1)
因为无论如何您都增加了价值!
添加“ else”块:
赞:
Dim name() As Variant
Dim jName as String
name = Split(ActiveCell,"-")
name(0) = name(0) + 1
jName = Join(name,"-")
Do Until Len(jName) = 8
jName = "0" & jName
Loop
ActiveCell.Offset(1, 0).Activate
ActiveCell.FormulaR1C1 = jName
输出:
def monG(borneinf,bornesup):
while True:
if bornesup < borneinf:
bornesup, borneinf = borneinf, bornesup
if borneinf==bornesup:
break
x=(yield borneinf)
if x is not None:
borneinf = x
else:
borneinf += 1
c=monG(2,10)
for a in c:
if a==5:
c.send(20)
print(a)