【问题标题】:unexpected output using yield statement使用 yield 语句的意外输出
【发布时间】:2021-07-26 14:57:20
【问题描述】:

我现在阅读了 return 和 yield 语句之间的区别并理解了一切,当我应用一些测试时,我遵循的教程说有 3 个选项我可以使用它来通过 yield 得到结果,其中一个是next 方法,如您所知,要使用 next 方法,您应该通过多次添加来手动创建它,我所做的测试是:

第一种情况:

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print(i)

这里的预期结果是:

0
1
4
9
16
25
36
49
64
81

它可以正常工作

第二种情况:

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print(next(sq))

所以,我没有多次打印下一个(sq),而是将它放入一个循环并使用它一次,所以它应该打印出与第一个函数相同的结果,而是打印出该结果:

1
9
25
49
81

我运行了调试,但我不明白到底发生了什么

【问题讨论】:

  • for i in sq 还在sq 上调用next,因此每个循环有效地调用next 两次。您编写第二个代码示例是否有原因?很少需要手动使用next
  • 这意味着结果应该循环,但是它打印了一次而不是两次

标签: python yield-return


【解决方案1】:

你在 for 循环中让步,然后立即用 next() 再次让步

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print("Before next: ", i)
    print("After next:  ", next(sq))

输出:

Before next:  0
After next:   1
Before next:  4
After next:   9
Before next:  16
After next:   25
Before next:  36
After next:   49
Before next:  64
After next:   81

【讨论】:

    【解决方案2】:

    代码for i in sq: 连续迭代迭代器的每个值,但在每次迭代中,您显式调用next 来获取下一个值,您忘记了i 中的值并继续前进,因此您打印一个值超过2

    sq = getSquare(10)
    for i in sq:
        print("current ", i)
        print("next:   ", next(sq))
    
    
    current  0
    next:    1
    current  4
    next:    9
    current  16
    next:    25
    current  36
    next:    49
    current  64
    next:    81
    

    要仅使用 next 来移动迭代器,请像这样使用并包装 try 以处理 StopIteration 错误

    sq = getSquare(10)
    try:
        while True:
            i = next(sq)
            print("current ", i)
    except StopIteration:
        print("End")
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多