python - 在 Python 中,为什么 itertools.cycle 需要额外的内存?

标签 python cycle python-itertools

<分区>

我很好奇 itertools.cycle(iterable) 中的警告:

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.

Equivalent to:

def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element

该条目还包含警告,“请注意,该工具包成员可能需要大量辅助存储(取决于可迭代对象的长度)。”

您能否通过以下方式避免额外的存储需求(和一些复杂性):

def cycle(iterable):
    while True:
        for i in iterable:
            yield i

saved 中存储用过的元素有什么好处?

最佳答案

一些可迭代对象只能被迭代一次。因此 cycle 将存储一个副本,以便它可以继续读取这些项目。 参见 this related question .

关于python - 在 Python 中,为什么 itertools.cycle 需要额外的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18478786/

相关文章:

python使用交互式解释器加载相对文件路径

javascript - 使用带有 .swf 嵌入的 jQuery 循环

python - 使用 itertools 从列表中进行组合

python - 如何在删除项目的同时循环遍历 Python 列表,直到没有剩余项目为止

python - 将 itertools.product 转换为列表时笛卡尔积内存错误

python - 车类错误

python - 是否可以在 SQLAlchemy 中创建一个可以创建父记录的事件监听器?

python - 如何在Python中循环遍历字母表索引?

python - 在 Python 中循环压缩多个列表

python - 使用 Python Requests 在请求之间设置新的 cookie