2016-07-16 63 views
2

我想要一個通過值列表無限循環的生成器。一種創建無限循環發生器的簡單方法?

這是我的解決方案,但我可能會錯過一個更明顯的解決方案。

成分:即拉平無限嵌套列表生成器功能,並且列表從屬於自己

def ge(x): 
    for it in x: 
     if isinstance(it, list): 
      yield from ge(it) 
     else: 
      yield(it) 


def infinitecyclegenerator(l): 
    x = l[:] 
    x.append(x) 
    yield from ge(x) 

使用:

g = infinitecyclegenerator([1,2,3]) 

next(g) #1 
next(g) #2 
next(g) #3 
next(g) #1 
next(g) #2 
next(g) #3 
next(g) #1 
... 

正如我所說的,我可能會丟失微不足道這樣做的方式,我會很高興學習。有沒有更好的方法?

此外,我是否應該擔心內存消耗,所有令人難以置信的無窮無盡在這裏,還是一切都很酷我的代碼?

回答

7

您可以使用itertools.cycle來達到同樣的效果

做一個迭代器返回從迭代元素和保存每一個 副本。當迭代器耗盡時,返回 保存的副本中的元素。

強調我的。您只關心內存將保存迭代器返回的每個項目的副本。

>>> from itertools import cycle 
>>> c = cycle([1,2,3]) 
>>> next(c) 
1 
>>> next(c) 
2 
>>> next(c) 
3 
>>> next(c) 
1 
>>> next(c) 
2 
>>> next(c) 
3 
0

它必須是小時:-)。一個顯而易見的方法我張貼後意識到:

def infinitecyclegenerator(l): 
    while True: 
     for it in l: 
      yield it 

對不起,缺少明顯。