【问题标题】:How do I print output values of generator functions?如何打印生成器函数的输出值?
【发布时间】:2021-01-21 02:46:29
【问题描述】:

我正在尝试打印使用 next() 时获得的生成器函数的产量。

我已经按照这个定义了一个函数:

import itertools

sequence = ['a', 'b', 'c', 'd']

def next_player(seq):
    yield itertools.cycle(seq)

现在,当我调用上述函数并使用 next()(例如 next(next_player(sequence)))时,我得到的是内存地址(例如 )。

如何打印列表中的实际值(例如“a”、“b”等)。我知道我可以使用“for”语句来迭代生成器对象,但我很好奇是否有另一种方法可以使用 next() 等来做到这一点。

【问题讨论】:

  • 您的意思是:return itertools.cycle(seq)
  • 当您必须在 for 循环中返回多个值时,您想使用 yield。例如,它使您不必附加到列表中。这里你只需要返回一次,所以你需要return,在这种情况下与yield from相同,因为你已经返回了一个生成器。

标签: python generator


【解决方案1】:

你希望你使用yield from:

import itertools

sequence = ['a', 'b', 'c', 'd']

def next_player(seq):
    yield from itertools.cycle(seq)

g = next_player(sequence)
for _ in range(6):
    print(next(g))

输出:

a
b
c
d
a
b

详细说明:yield from 可以链接interables,在这种情况下,它与写作相同:

def next_player(seq):
    for x in itertools.cycle(seq):
        yield x

但是由于itertools.cycle 已经返回了一个类似生成器的对象,你可以写

def next_player(seq):
    return itertools.cycle(seq)

【讨论】:

    【解决方案2】:

    另一个选项是在函数之前声明循环:

    from itertools import cycle
    sequence = ['a', 'b', 'c', 'd']
    cycle_sequence = cycle(sequence)
    
    def next_item():
        return next(cycle_sequence)
    

    然后使用它:

    for _ in range(9):
        n = next_item()
        print(n)
    

    将打印:

    a
    b
    c
    d
    a
    b
    c
    d
    a
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多