我正在寻找将常规迭代器转换为支持将项目推回到其中的常规迭代器的原因。 E.g。
double shipping = 0.0;
这与支持item = next(my_iterator)
if went_too_far(item):
my_iterator.pushback(item)
break;
的迭代器类似,但不完全相同;对于后者,上面看起来更像是这样:
peek
答案 0 :(得分:2)
class PushbackWrapper(object):
def __init__(self, iterator):
self.__dict__['_iterator'] = iterator
self.__dict__['_pushed'] = []
def next(self):
if len(self._pushed):
return self._pushed.pop()
else:
return self._iterator.next()
def pushback(self, item):
self._pushed.append(item)
def __getattr__(self, attr):
return getattr(self._iterator, attr)
def __setattr__(self, attr, value):
return setattr(self._iterator, attr, value)
使用它:
pushback_enabled_iterator = PushbackWrapper(original_iterator)
item = next(pushback_enabled_iterator)
if went_too_far(item):
pushback_enabled_iterator.pushback(item)
break;