使用 itertools 进行一行重复计数器?

ale*_*dro 2 python python-itertools

我想使用 itertools 编写一个无限生成器,它结合了 thecountrepeat迭代器,在递增之前重复每个数字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
Run Code Online (Sandbox Code Playgroud)

Ry-*_*Ry- 5

使用整数除法!

def repeating_counter(times):
    return (x // times for x in count())
Run Code Online (Sandbox Code Playgroud)