I have a list of generators in a function alternate_all(*args)
that alternates between each generator in the list to print their first item, second item, ..., etc. until all generators are exhausted.
My code works until a generator is exhausted and once the StopIteration occurs, it stops printing, when I want it to continue with the rest of the generators and ignore the exhausted one:
def alternate_all(*args):
iter_list = []
for iterable in args:
iter_list.append(iter(iterable))
try:
while True:
for iterable in iter_list:
val = next(iter_list[0])
iter_list.append(iter_list.pop(0))
yield val
except StopIteration:
pass
if __name__ == '__main__':
for i in alternate_all('abcde','fg','hijk'):
print(i,end='')
My output is:
afhbgic
When it should be:
afhbgicjdke
How can I get this to ignore the exhausted generator? I would prefer not to use itertools and keep this same structure.
itertools.zip_longest
?StopIteration
exception innext(iter_list[0])
if the iterator has been exhausted. You should catch and handle it.while
loop so that it keepsyield
ing. You should then implement the logic to quit when all iterators are exhausted.map
with named functions. I honestly don't understand Guido's hate formap()
.