【问题标题】:Python generators and yield - increment to the next() call in a while loopPython 生成器和 yield - 在 while 循环中递增到 next() 调用
【发布时间】:2021-11-04 20:43:48
【问题描述】:

在下面的代码 sn-p 中,您将如何使用运算符 += 而不是键入四次 print(next(seq)) 来增加 next() 调用?在while 循环中,只有print(next(seq)) 的第一个实例会重复打印。每次迭代如何推进到下一个?

def get_sequence_upto(x):
    for i in range(x):
        yield i 

seq = get_sequence_upto(5)

print(next(seq))

print(next(seq))

print(next(seq))

print(next(seq))

输出:

0
1
2
3

编辑:添加了while循环sn-p

while True:
seq = loop_here(x)

        print(next(seq))

我尝试将 += 添加到代码中的不同点,但没有成功。

【问题讨论】:

  • With this in a while loop, only the first instance of print(next(seq)) will print repeatedly 不,这不会发生,因为您没有将 seq = get_sequence_upto(5) 放入 while 循环中。
  • 对不起,while循环的代码有点不同,但概念是一样的。
  • 请提供代码
  • 我添加了 while 循环部分 - 谢谢
  • 请将seq = loop_here(x) 保留在while 循环之外,您将在循环的每次迭代中重新初始化seq。另外最好使用For ... in,否则你必须用try ... except处理StopIteration异常

标签: python python-3.x while-loop generator yield


【解决方案1】:

你可以像下面这样使用for循环:

def get_sequence_upto(x):
    for i in range(x):
        yield i 

seq = get_sequence_upto(5)
while seq:
    try:
        print(next(seq))
    except:
        break

【讨论】:

  • 感谢您的宝贵时间和回答 - 我意识到我问错了问题 - 我编辑了问题以包含 while 循环部分
  • @LeoOptimoII 你需要什么?需要while循环
  • 我需要 while 循环 - for 部分具有误导性。我将再次编辑问题。谢谢大家。
  • @LeoOptimoII 我编辑我的答案是否正确?
  • 是的 - 我意识到我问错了问题。
【解决方案2】:

在 for 循环中使用 yield from:

def get_sequence_upto(x):
    yield from range(x)

nums = get_sequence_upto(5)
while True:
    x = next(nums, None)
    if x is not None:
        print(x)
        continue
    break

或者tryexcept:

def get_sequence_upto(x):
    yield from range(x)

nums = get_sequence_upto(5)
while True:
    try:
        print(next(nums))
    except StopIteration:
        break

【讨论】:

  • 谢谢!我意识到我错误地问了这个问题 - 抱歉,我的问题是在 while 循环部分。我编辑了问题。
  • @LeoOptimoII 编辑了我的答案现在应该可以工作了
  • @LeoOptimoII 编辑了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多