G
Guest
Given a list of iterators, I'd like to have a new one that would
cyclically walk over the list calling the next() method of the iterators
(removing any iterator which is exhausted). It should also support adding
a new iterator to the list; it should be added in front of the current
position (so that it's called only after all the others). This is what I
was able to write with my zero python skills (self.iters is the list of
iterators, self.i is the index of the iterator that should be used next).
Is there a nicer/more pythonic solution, maybe using generators?
class Liter(object):
def __init__(self, *iters):
self.i=0
self.iters=[iter(x) for x in iters]
def append(self,what):
self.iters.insert(self.i,what)
def __iter__(self):
return self
def next(self):
while True:
try:
result=self.iters[self.i].next()
except StopIteration:
del self.iters[self.i]
except IndexError:
if len(self.iters) is 0:
raise StopIteration
else:
self.i=0
else:
self.i+=1
return result
cyclically walk over the list calling the next() method of the iterators
(removing any iterator which is exhausted). It should also support adding
a new iterator to the list; it should be added in front of the current
position (so that it's called only after all the others). This is what I
was able to write with my zero python skills (self.iters is the list of
iterators, self.i is the index of the iterator that should be used next).
Is there a nicer/more pythonic solution, maybe using generators?
class Liter(object):
def __init__(self, *iters):
self.i=0
self.iters=[iter(x) for x in iters]
def append(self,what):
self.iters.insert(self.i,what)
def __iter__(self):
return self
def next(self):
while True:
try:
result=self.iters[self.i].next()
except StopIteration:
del self.iters[self.i]
except IndexError:
if len(self.iters) is 0:
raise StopIteration
else:
self.i=0
else:
self.i+=1
return result