python - 修改 Itertools.cycle()

标签 python cycle python-itertools

我目前正在使用 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()

关于python - 修改 Itertools.cycle(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24438153/

相关文章:

c++ - 什么是奇长循环,我如何知道我的图表中是否存在奇数循环?

python - 当用 operator.itemgetter 填充时,itertools.groupby 返回空列表项

python - 如何使用 itertools.groupby 将 CSV 数据转换为字典

python - 列表中 Python 中的无序对(对集)

python - 如何分析此 Pandas DataFrame 中的所有重复条目?

python - 如何从 django forms.Form 中排除字段?

python - 保持 python 调度程序脚本在 Windows 上运行

python - Pandas 数据框可对多列和要列出的值进行字典

javascript - jQuery Cycle 插件在第一个循环后停止在第一张幻灯片上

css - 如何使 SVG 路径中的文本居中