gpt4 book ai didi

python - 使用 f.next() 迭代时倒带多行

转载 作者:行者123 更新时间:2023-12-05 06:43:24 25 4
gpt4 key购买 nike

this question跟进.如何修改此代码以允许倒带多行?

class rewindable_iterator(object):    not_started = object()    def __init__(self, iterator):        self._iter = iter(iterator)        self._use_save = False        self._save = self.not_started    def __iter__(self):        return self    def next(self):        if self._use_save:            self._use_save = False        else:            self._save = self._iter.next()        return self._save    def backup(self):        if self._use_save:            raise RuntimeError("Tried to backup more than one step.")        elif self._save is self.not_started:            raise RuntimeError("Can't backup past the beginning.")        self._use_save = True

最佳答案

这是我想出的解决方案:

from collections import deque
class rewindable_iterator(object):
not_started = object()

def __init__(self, filename,deque_max_length=2):
self._f=open(filename,'r')
self._iter = iter(self._f)
self._use_save = False
# self._use_save2 = False
self._save = self.not_started
self._use_num=0
self._deque=deque([],deque_max_length)

def __iter__(self):
return self
def __enter__(self):
return self
def readline(self):
return self._iter.readline()

def __exit__(self,exc_type, exc_value, traceback):
if exc_type is not None:
print exc_type, exc_value, traceback
self._f.close()

def next(self):
if self._use_save:
self._use_num -= 1
if not self._use_num:
self._use_save = False
return self._deque[-self._use_num-1]
else:
self._save = self._iter.next()
self._deque.append(self._save)
return self._save

def backup(self,num=2):

if self._use_num+num>len(self._deque):
raise RuntimeError("Tried to backup more than the available lines")
elif self._save is self.not_started:
raise RuntimeError("Can't backup past the beginning.")
self._use_save = True
self._use_num+=num

关于python - 使用 f.next() 迭代时倒带多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com