我正在创建interator
,如此:
some_list = [1,2,5,12,30,75,180,440]
iter(some_list)
我需要再次访问迭代器的当前值。是否有current()
方法可以让我保持相同的位置?
答案 0 :(得分: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)
问题是你为什么要这样做?
答案 1 :(得分: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
答案 2 :(得分:0)
改编this answer的第三个例子:
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
,因此如果不存在当前值,则可以引发错误property
使current
看起来像一个简单的属性__next__
和next = __next__
进行Python 2& 3兼容性