gpt4 book ai didi

python - 支持回推的迭代器

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:53 24 4
gpt4 key购买 nike

我正在寻找将常规迭代器转换为支持将项目推回其中的迭代器的原因。例如

item = next(my_iterator)
if went_too_far(item):
my_iterator.pushback(item)
break;

这与支持peek 的迭代器类似,但不完全相同;对于后者,上面的内容看起来更像这样:

if went_too_far(my_iterator.peek()):
break
else:
item = next(my_iterator)

最佳答案

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;

关于python - 支持回推的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35664103/

24 4 0