Skip to main content
 首页 » 编程设计

python之修改 Itertools.cycle()

2025年05月04日15mayingbao

我目前正在使用 itertools.cycle() 对象,我想知道在创建循环后是否可以修改循环。以下内容:

my_cycle = itertools.cycle([1,2,3]) 
print my_cycle.next() 
my_cycle.delete()    #function doesn't exist 
print my_cycle.next() 

将有一个输出:

1 
3 

有什么办法可以通过itertools实现吗?或者也许是另一个对象?或者我是否需要实现自己的对象才能执行此操作。

请您参考如下方法:

Itertools 不提供这样的选项。您可以使用 deque 构建它:

from collections import deque 
 
class ModifiableCycle(object): 
    def __init__(self, items=()): 
        self.deque = deque(items) 
    def __iter__(self): 
        return self 
    def __next__(self): 
        if not self.deque: 
            raise StopIteration 
        item = self.deque.popleft() 
        self.deque.append(item) 
        return item 
    next = __next__ 
    def delete_next(self): 
        self.deque.popleft() 
    def delete_prev(self): 
        # Deletes the item just returned. 
        # I suspect this will be more useful than the other method. 
        self.deque.pop()