python - 我怎样才能懒惰地构建一个列表?

标签 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

最佳答案

将您的生成器包装在一个缓存生成的结果的对象中:

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

关于python - 我怎样才能懒惰地构建一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668668/

相关文章:

python - 用于 Ruby 或 Python 的 Git 库?

python - 如何使用Python SDK for Azure获取存储帐户中文件的Etag?

python - 使用 pydrive 模块在 Gdrive 上创建新文件夹

python - Jinja2 为 Google App Engine 模型返回 "None"字符串

python - 使用 python 正则表达式匹配文件名末尾的 "~"

python - Unpickle 二进制文件到文本

python - 如何在 Pandas Dataframe 中跨行和列累积链接值?

python - 我如何使用python(pywin32)更改word中表格的大小

python - 消除for循环中的 "found"变量

python - pip 或 pip3 installrequirements.txt 的问题我应该做什么来修复此错误?