Skip to main content
 首页 » 编程设计

python之带有 itertools 的一行重复计数器

2025年05月04日36虾米姐

我想使用 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())