ale*_*dro 2 python python-itertools
我想使用 itertools 编写一个无限生成器,它结合了 thecount和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
Run Code Online (Sandbox Code Playgroud)
使用整数除法!
def repeating_counter(times):
return (x // times for x in count())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |