【问题标题】:Using yield won't generate new numbers (Using next function)使用 yield 不会生成新数字(使用 next 函数)
【发布时间】:2021-12-28 05:32:13
【问题描述】:

我正在尝试使用 yield 在每次迭代中生成新数字,如下所示:

def nextSquare():
    i = 1
  
    # An Infinite loop to generate squares 
    while True:
        yield i*i                
        i += 1  # Next execution resumes 
                # from this point

当我尝试时:

>>> for num in nextSquare():
    if num > 100:
         break    
    print(num)

我得到了想要的输出:

1
4
9
16
25
36
49
64
81
100

但是当我尝试时: next(nextSquare())

它总是产生相同的旧结果。难道我做错了什么?我感兴趣的是按需生成,而不是在 for 循环中生成新数字。

【问题讨论】:

  • 每次你调用 nextSquare,你都会得到一个新的迭代器。如果您想从同一个迭代器中获取多个值,请使用例如square = nextSquare() 一次然后next(square) 多次。

标签: python yield-from


【解决方案1】:

根据 cmets 的建议,每次调用 nextSquare 都会生成一个新的迭代器,因此我将代码更改为:

gen = nextSquare()

next(gen) 的按需调用会产生预期的结果。

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 2021-09-05
    • 2021-10-29
    • 2014-01-25
    • 2018-01-23
    • 1970-01-01
    • 2016-05-04
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多