我想使用 itertools 编写一个无限生成器,它结合了 count 和 repeat 迭代器,通过在递增之前重复每个数字 n 次.有没有比我想出的更简洁的方法呢?
from itertools import *
def repeating_counter(times):
c = count()
while True:
for x in repeat(next(c), times):
yield x
>>> rc = repeating_counter(2)
>>> next(rc)
0
>>> next(rc)
0
>>> next(rc)
1
>>> next(rc)
1
请您参考如下方法:
使用整数除法!
def repeating_counter(times):
return (x // times for x in count())
