1

我正在创建一个interator这样的:

some_list = [1,2,5,12,30,75,180,440]
iter(some_list)

我需要再次访问迭代器的当前值。有没有一种current()方法可以让我保持在同一个位置?

4

3 回答 3

1

您当然可以创建一个允许您执行此操作的课程:

from collections import deque

class RepeatableIter(object):
    def __init__(self,iterable):
        self.iter = iter(iterable)
        self.deque = deque([])
    def __iter__(self):
        return self

    #define `next` and `__next__` for forward/backward compatability
    def next(self):
        if self.deque:
            return self.deque.popleft()
        else:
            return next(self.iter)
    __next__ = next

    def requeue(self,what):
        self.deque.append(what)


x = RepeatableIter([1, 2, 3, 4, 5, 6])
count = 0
for i in x:
    print i
    if i == 4 and count == 0:
        count += 1
        x.requeue(i)

问题是你为什么要这么做?

于 2013-04-23T02:02:12.060 回答
0

你可以用它numpy.nditer来构建你的迭代器,然后你有很多很棒的选项,包括当前的value.

import numpy

rng = range(100)
itr = numpy.nditer([rng])
print itr.next()          #0
print itr.next()          #1
print itr.next()          #2

print itr.value           #2 : current iterator value
于 2013-04-23T02:23:54.223 回答
0

从这个答案改编第三个例子:

class CurrentIterator():

    _sentinal = object()
    _current = _sentinal

    @property
    def current(self):
        if self._current is self._sentinal:
            raise ValueError('No current value')
        return self._current

    def __init__(self, iterable):
        self.it = iter(iterable)

    def __iter__(self):
        return self

    def __next__(self):
        try:
            self._current = current = next(self.it)
        except StopIteration:
            self._current = self._sentinal
            raise
        return current
    next = __next__  # for python2.7 compatibility

一些有趣的观点:

  • 如果当前值不存在,使用_sentinalso 会引发错误
  • 使用propertysocurrent看起来像一个简单的属性
  • Python 2&3 兼容性的使用__next__next = __next__
于 2016-03-25T20:14:27.057 回答