python重复迭代器中的列表元素

zha*_*eng 0 python python-itertools

有没有办法创建迭代器来重复列表中的元素某些时间?例如,列出了一个列表:

color = ['r', 'g', 'b']
Run Code Online (Sandbox Code Playgroud)

有没有办法以itertools.repeatlist(color, 7)可以生成以下列表的形式创建迭代器?

color_list = ['r', 'g', 'b', 'r', 'g', 'b', 'r']
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 10

您可以itertools.cycle()与您一起使用itertools.islice()来构建您的repeatlist()功能:

from itertools import cycle, islice

def repeatlist(it, count):
    return islice(cycle(it), count)
Run Code Online (Sandbox Code Playgroud)

这将返回一个新的迭代器; list()如果你必须有一个列表对象,请调用它.

演示:

>>> from itertools import cycle, islice
>>> def repeatlist(it, count):
...     return islice(cycle(it), count)
...
>>> color = ['r', 'g', 'b']
>>> list(repeatlist(color, 7))
['r', 'g', 'b', 'r', 'g', 'b', 'r']
Run Code Online (Sandbox Code Playgroud)