2014-09-04 33 views
1

我希望能夠推遲列表元素的構造,直到他們第一次被訪問。顯而易見的解決方案(使用下面的生成器不起作用,因爲它可以迭代多次,等等)。我該如何懶散地構建一個列表?

例如,以下打印0 - > 9.我想兩次打印0-> 9。

def costly_build_function(i): 
    return i 
def my_function(): 
    return (costly_build_function(i) for i in range(0,10)) 
tmp = my_function() 
# print 0 to 0 
for i in tmp: 
    print i 
# print nothing 
for i in tmp: 
    print i 

回答

4

環繞你發生器在緩存結果產生的對象:

class LazyList(object): 
    def __init__(self, it): 
     self._cache = [] 
     self._it = it 
    def __iter__(self): 
     for item in self._cache: 
      yield item 
     for item in self._it: 
      self._cache.append(item) 
      yield item