我使用Python來無限地遍歷列表,重複列表中的每個元素多次。例如給出的列表:如何迭代重複Python中的每個元素的列表
l = [1, 2, 3, 4]
我想兩次輸出的每個元素,然後重複循環:
1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ...
我得從哪裏開始的想法:
def cycle(iterable):
if not hasattr(cycle, 'state'):
cycle.state = itertools.cycle(iterable)
return cycle.next()
>>> l = [1, 2, 3, 4]
>>> cycle(l)
1
>>> cycle(l)
2
>>> cycle(l)
3
>>> cycle(l)
4
>>> cycle(l)
1
但是,我會如何重複每個元素?
編輯
爲了澄清這應該無限循環。我也用過兩次重複元素作爲最短的例子 - 我真的很想重複每個元素n次。
更新
您的解決方案使我什麼,我一直在尋找:
>>> import itertools
>>> def ncycle(iterable, n):
... for item in itertools.cycle(iterable):
... for i in range(n):
... yield item
>>> a = ncycle([1,2], 2)
>>> a.next()
1
>>> a.next()
1
>>> a.next()
2
>>> a.next()
2
>>> a.next()
1
>>> a.next()
1
>>> a.next()
2
>>> a.next()
2
感謝您的快速解答!
當你要它停止? – 2008-12-20 18:30:25