取之不尽的发电机

时间:2018-08-07 03:06:25

标签: python-3.x

我想创建一个无穷无尽的生成器,该生成器总是使用itertools中的值返回数字4。示例输出如下。

number = number_4()

next(number) == 4
    True
next(number) == 4
    True
next(number)
    4
next(number)
    4
next(number)
    4

此代码是否不起作用?

def number_4(): 
    """Return a generator that always returns the number 4"""
    itertools.repeat(4) = infinite
    return infinite

number = number_4()
print(next(number) == 4)
print(next(number))

1 个答案:

答案 0 :(得分:3)

您正在描述itertools.repeat的基本用法。

>>> four = itertools.repeat(4)
>>> next(four)
4
>>> next(four)
4