我想创建一个无穷无尽的生成器,该生成器总是使用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))
答案 0 :(得分:3)
您正在描述itertools.repeat
的基本用法。
>>> four = itertools.repeat(4)
>>> next(four)
4
>>> next(four)
4