Skip to main content
 首页 » 编程设计

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

2025年05月04日10lovecherry

<分区>

我很好奇 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 中存储用过的元素有什么好处?