我正在使用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
感谢您的快速解答!
答案 0 :(得分: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)]
编辑:合并bishanty's重复计数参数和Adam Rosenfield's list comprehension。
答案 1 :(得分: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]
答案 2 :(得分:2)
itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l))
答案 3 :(得分:1)
解决方案应该是
iterable = [1, 2, 3, 4]
n = 2
while (True):
for elem in iterable:
for dummy in range(n):
print elem # or call function, or whatever
编辑:添加'While(True)'无限期迭代。
答案 4 :(得分:1)
import itertools as it
def ncycle(iterable, n=1):
if n == 1:
return it.cycle(iterable)
return it.cycle(it.chain(*it.izip(*([iterable]*n))))
答案 5 :(得分:1)
我是这样做的:
from itertools import cycle, repeat, chain
flatten = chain.from_iterable # better name
def ncycle(xs, n):
return flatten(repeat(x, n) for x in cycle(xs))
# example
for n,x in enumerate(ncycle('abcd', 2)):
print(x, end=" ")
if n > 9:
print("")
break
# output: a a b b c c d d a a b
答案 6 :(得分:0)
[ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4]
最后4个循环次数。