简体   繁体   English

修改Itertools.cycle()

[英]Modify Itertools.cycle()

I'm currently using the itertools.cycle() object, and I was wondering if there was anyway to modify the cycle after it's creation. 我当前使用的是itertools.cycle()对象,我想知道在创建之后是否仍然可以修改该循环。 The following: 下列:

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

would have an output of: 输出为:

1
3

Is there any way to achieve this through itertools? 有什么办法可以通过itertools实现这一目标吗? Or perhaps another object? 还是另一个对象? Or do I need to implement my own object to do this. 还是我需要实现自己的对象才能做到这一点。

Itertools doesn't provide such an option. Itertools不提供此类选项。 You can build it with a 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()

If you want to skip over a value you can just call next once. 如果你想跳过一个值,你可以叫next一次。

If you want to permanently remove one of the values from the cycle, by value, you can create a generator. 如果要按值从循环中永久删除值之一,则可以创建一个生成器。

def skip_matching(gen, value):
    for v in gen:
        if v == value:
            continue
        yield v

Then you can wrap a cycle like so: 然后,您可以像这样包装一个循环:

>>> a = skip_matching(itertools.cycle([1,2,3]), 2)
>>> a.next()
1
>>> a.next()
3
>>> a.next()
1

If you want to remove the next value by position (without removing any others that match it), you have to know the cycle length n. 如果要按位置删除下一个值(而不删除与其匹配的其他任何值),则必须知道循环长度n。 Then you can skip one and collect n-1 to create a new cycle. 然后,您可以跳过一个并收集n-1来创建一个新循环。

c.next()
c = itertools.cycle(c.next() for i in range(n-1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM