来自 itertools.cycle 生成器的列表理解

List comprehension from itertools.cycle generator

我的问题是我需要从 itertools.cycle 生成器以列表形式交付批次。

A cycle 接受一个可迭代对象并无限期地围绕自身循环。例如:

>>> my_cycle = itertools.cycle('abc')
>>> next(my_cycle)
'a'
>>> next(my_cycle)
'b'
>>> next(my_cycle)
'c'
>>> next(my_cycle)
'a'

等等。

问题就变成了,我们如何从循环生成器中传递批量长度 n 的列表,同时保留我们在循环中的位置?

期望的输出是:

c = itertools.cycle('abc')
batch_size = 2
Out[0]: ['a', 'b']
Out[1]: ['c', 'a']
Out[2]: ['b', 'c']

我正在发布我的解决方案,以防有人遇到同样的问题。

>>> size_of_batch = 5
>>> c = itertools.cycle('abcdefg')
>>> [next(c) for _ in range(size_of_batch)]

['a', 'b', 'c', 'd', 'e']

>>> [next(c) for _ in range(size_of_batch)]

['f', 'g', 'a', 'b', 'c']

似乎 islice 就是为此而生的:

>>> from itertools import cycle, islice
>>> size_of_batch = 5
>>> c = cycle('abcdefg')
>>> list(islice(c, size_of_batch))
['a', 'b', 'c', 'd', 'e']
>>> list(islice(c, size_of_batch))
['f', 'g', 'a', 'b', 'c']

有一个 itertools recipe 专门为此设计的:

from itertools import islice, cycle


def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))


c = cycle("abcdefg")
take(5, c)
# ['a', 'b', 'c', 'd', 'e']