如何迭代重复Python中每个元素的列表

jb.*_*jb. 8 python iterator

我正在使用Python 无限遍历列表,重复列表中的每个元素很多次.例如给出列表:

l = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我想输出每个元素两次,然后重复循环:

1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... 
Run Code Online (Sandbox Code Playgroud)

我知道从哪里开始:

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
Run Code Online (Sandbox Code Playgroud)

但是,我将如何重复每个元素?

编辑

澄清这应该无限迭代.另外我用两次重复元素作为最短的例子 - 我真的想重复每个元素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
Run Code Online (Sandbox Code Playgroud)

谢谢你的快速解答!

Wil*_*ris 13

这个怎么样:

import itertools

def bicycle(iterable, repeat=1):
    for item in itertools.cycle(iterable):
        for _ in xrange(repeat):
            yield item

c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]
Run Code Online (Sandbox Code Playgroud)

编辑:纳入bishanty的重复计数参数和亚当罗森菲尔德的列表理解.


Ada*_*eld 6

你可以很容易地使用生成器:

def cycle(iterable):
    while True:
        for item in iterable:
            yield item
            yield item

x=[1,2,3]
c=cycle(x)

print [c.next() for i in range(10)]  // prints out [1,1,2,2,3,3,1,1,2,2]
Run Code Online (Sandbox Code Playgroud)