2014-09-04 21 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 
相关问题