我该如何懒惰地构建一个列表?

时间:2014-09-04 14:54:40

标签: python

我希望能够推迟列表元素的构造,直到第一次访问它们为止。显而易见的解决方案(使用如下的生成器不起作用,因为它可以多次迭代,等等)。

例如,以下打印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

1 个答案:

答案 0 :(得分: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
相关问题