2008-12-20 97 views
6

我使用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 

感謝您的快速解答!

+0

當你要它停止? – 2008-12-20 18:30:25

回答

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

解決方案應該是這樣的

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 

編輯:添加 '而(真)' 無限期地重複。

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] 
+0

再一次,我不是100%肯定已經理解了這個問題,但是對於像返回一個項目兩次(或n次)這樣的簡單問題,生成器不是一個矯枉過正的問題? – 2008-12-20 18:38:15

+0

這是5行。這怎麼可能矯枉過正?如果替代方案是建立一個列表,那是不可能的,因爲它的長度是無限的。 – recursive 2008-12-22 20:26:24

0
[ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4] 

最後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)))) 
0
itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l)) 
0

我做這種方式:

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 
相關問題