我创建了一个生成器,我希望根据给定的长度获得子生成器。 我有一个函数,但我想知道itertools模块中是否还有更多的pythonic方法:
def create_sub_generators(generator, length=10):
to_return = []
for index, element in enumerate(generator):
if (index % length) == 0 and index > 0:
yield iter(to_return)
to_return = []
to_return.append(element)
yield iter(to_return)
a = (i for i in range(100))
for index, lengh in enumerate(create_sub_generators(a, 22)):
print(f'generator num: {index} lenght: {len([i for i in lengh])}')
generator num: 0 lenght: 22
generator num: 1 lenght: 22
generator num: 2 lenght: 22
generator num: 3 lenght: 22
generator num: 4 lenght: 12