python 在迭代器中重复列表元素
python repeat list elements in an iterator
有没有办法创建一个迭代器来重复列表中的元素一定次数?例如给出一个列表:
color = ['r', 'g', 'b']
有没有办法创建一个 itertools.repeatlist(color, 7)
形式的迭代器,它可以产生以下列表?
color_list = ['r', 'g', 'b', 'r', 'g', 'b', 'r']
您可以使用 itertools.cycle()
together with itertools.islice()
构建您的 repeatlist()
函数:
from itertools import cycle, islice
def repeatlist(it, count):
return islice(cycle(it), count)
这个returns一个新的迭代器;如果您必须有一个列表对象,请对其调用 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']
cycle
的文档说:
Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).
我很好奇为什么 python 没有提供更有效的实现:
def cycle(it):
while True:
for x in it:
yield x
def repeatlist(it, count):
return [x for (i, x) in zip(range(count), cycle(it))]
这样,您就不需要保存列表的整个副本。如果列表无限长,它也有效。
有没有办法创建一个迭代器来重复列表中的元素一定次数?例如给出一个列表:
color = ['r', 'g', 'b']
有没有办法创建一个 itertools.repeatlist(color, 7)
形式的迭代器,它可以产生以下列表?
color_list = ['r', 'g', 'b', 'r', 'g', 'b', 'r']
您可以使用 itertools.cycle()
together with itertools.islice()
构建您的 repeatlist()
函数:
from itertools import cycle, islice
def repeatlist(it, count):
return islice(cycle(it), count)
这个returns一个新的迭代器;如果您必须有一个列表对象,请对其调用 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']
cycle
的文档说:
Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).
我很好奇为什么 python 没有提供更有效的实现:
def cycle(it):
while True:
for x in it:
yield x
def repeatlist(it, count):
return [x for (i, x) in zip(range(count), cycle(it))]
这样,您就不需要保存列表的整个副本。如果列表无限长,它也有效。