我正在创建一个interator
这样的:
some_list = [1,2,5,12,30,75,180,440]
iter(some_list)
我需要再次访问迭代器的当前值。有没有一种current()
方法可以让我保持在同一个位置?
您当然可以创建一个允许您执行此操作的课程:
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)
问题是你为什么要这么做?
你可以用它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
从这个答案改编第三个例子:
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
一些有趣的观点:
_sentinal
so 会引发错误property
socurrent
看起来像一个简单的属性__next__
和next = __next__