从itertools.cycle中提取列表

6
我有一个包含 itertools.cycle 实例的类,我希望能够复制它。其中一种方法(也是我能想到的唯一一种方法)是提取初始可迭代对象(即一个列表),并存储循环所在的位置。
不幸的是,我无法得到用于创建循环实例的列表,也没有明显的方法可以实现这一点。
import itertools
c = itertools.cycle([1, 2, 3])
print dir(c)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
 '__hash__', '__init__', '__iter__', '__new__', '__reduce__', 
 '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
 '__subclasshook__', 'next']

我可以想出一些半合理的理由来解释为什么对于某些类型的输入可迭代对象会被禁止,但是对于元组或者可能甚至是列表(这里可能存在可变性问题),我不明白为什么不可能实现。
有人知道是否可以从一个itertools.cycle实例中提取出非无限的可迭代对象。如果不行,有人知道为什么这个想法不可行吗?

2
为什么需要这个?要复制实例,只需使用相同的源列表重新创建即可(可以将源列表保存在其他地方)。但是,这会创建一个新的迭代器。请记住,迭代器包含比源可迭代对象更多的状态,例如序列中的当前位置。 - Niklas B.
1
你考虑过查看 itertools.tee 吗?根据你的需求,我认为你可以运用 myiter,copy = itertools.tee(myiter) 这样的语句。 - mgilson
1
说真的,你为什么需要这样做?我倾向于认为你的设计过程存在缺陷。 - inspectorG4dget
1
并不是说它被“禁止”,只是cycle()没有这个功能。此外,cycle是用C实现的,所以要“黑客”内部并不容易。 - Joel Cornett
4个回答

5

这是不可能的。如果你查看itertools.cycle代码,你会发现它并没有存储序列的副本。它只创建了一个可迭代对象,并将可迭代对象中包含的值存储在新创建的列表中:

static PyObject *
cycle_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *it;
    PyObject *iterable;
    PyObject *saved;
    cycleobject *lz;

    if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
        return NULL;

    if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
        return NULL;
    /* NOTE: they do not store the *sequence*, only the iterator */
    /* Get iterator. */
    it = PyObject_GetIter(iterable);
    if (it == NULL)
        return NULL;

    saved = PyList_New(0);
    if (saved == NULL) {
        Py_DECREF(it);
        return NULL;
    }

    /* create cycleobject structure */
    lz = (cycleobject *)type->tp_alloc(type, 0);
    if (lz == NULL) {
        Py_DECREF(it);
        Py_DECREF(saved);
        return NULL;
    }
    lz->it = it;
    lz->saved = saved;
    lz->firstpass = 0;

    return (PyObject *)lz;
}

这意味着在进行以下操作时:
itertools.cycle([1,2,3])

你创建的列表只有一个引用,这个引用保存在循环中使用的迭代器中。当迭代器被耗尽时,迭代器会被删除并创建一个新的迭代器。
    /* taken from the "cycle.next" implementation */
    it = PyObject_GetIter(lz->saved);
    if (it == NULL)
        return NULL;
    tmp = lz->it;
    lz->it = it;
    lz->firstpass = 1;
    Py_DECREF(tmp);   /* destroys the old iterator */

这意味着在执行完一次循环后,列表将被销毁。
如果需要访问此列表,请在调用 itertools.cycle 之前将其引用到某个地方。

0

根据您使用cycle的方式,您甚至可以使用如下简单的自定义类包装器:

class SmartCycle:
    def __init__(self, x):
        self.cycle = cycle(x)
        self.to_list = x

    def __next__(self):
        return next(self.cycle)

例如

> a = SmartCycle([1, 2, 3])
> for _ in range(4):
>     print(next(a))
1
2
3
1

> a.to_list
[1, 2, 3]

0

好的,我已经接受了@Bakuriu的答案,因为它在技术上是正确的。不可能复制/序列化一个itertools.cycle对象。

我实现了一个itertools.cycle的子类,可以进行序列化(还带有一些额外的功能)。

import itertools


class FiniteCycle(itertools.cycle):
    """
    Cycles the given finite iterable indefinitely. 
    Subclasses ``itertools.cycle`` and adds pickle support.
    """
    def __init__(self, finite_iterable):
        self._index = 0
        self._iterable = tuple(finite_iterable)
        self._iterable_len = len(self._iterable)
        itertools.cycle.__init__(self, self._iterable)

    @property
    def index(self):
        return self._index

    @index.setter
    def index(self, index):
        """
        Sets the current index into the iterable. 
        Keeps the underlying cycle in sync.

        Negative indexing supported (will be converted to a positive index).
        """
        index = int(index)
        if index < 0:
            index = self._iterable_len + index
            if index < 0:
                raise ValueError('Negative index is larger than the iterable length.')

        if index > self._iterable_len - 1:
            raise IndexError('Index is too high for the iterable. Tried %s, iterable '
                             'length %s.' % (index, self._iterable_len))

        # calculate the positive number of times the iterable will need to be moved
        # forward to get to the desired index
        delta = (index + self._iterable_len - self.index) % (self._iterable_len)

        # move the finite cycle on ``delta`` times.
        for _ in xrange(delta):
            self.next()

    def next(self):
        self._index += 1
        if self._index >= self._iterable_len:
            self._index = 0
        return itertools.cycle.next(self)

    def peek(self):
        """
        Return the next value in the cycle without moving the iterable forward.
        """
        return self._iterable[self.index]

    def __reduce__(self):
        return (FiniteCycle, (self._iterable, ), {'index': self.index})

    def __setstate__(self, state):
        self.index = state.pop('index')

一些使用示例:

c = FiniteCycle([1, 2, 3])

c.index = -1
print c.next() # prints 3

print [c.next() for _ in xrange(4)] # prints [1, 2, 3, 1]

print c.peek() # prints 2
print c.next() # prints 2

import pickle
import cStringIO
serialised_cycle = pickle.dumps(c)

del c

c = pickle.loads(serialised_cycle)

print c.next() # prints 3
print c.next() # prints 1

欢迎提供反馈意见。

谢谢,


0

如果您知道由cycle生成的对象的某些属性,则可以推断出内部列表。例如,如果您知道循环中的所有对象都是不同的,并且除了您之外没有其他内容从cycle迭代器读取,则可以简单地等待您看到的第一个对象再次出现(使用is而不是==进行测试)以终止内部列表。

但是,如果没有这样的知识,则没有任何保证,您选择猜测循环的方法将在某些情况下失败。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接