Skip to content

Instantly share code, notes, and snippets.

@Bezoar
Last active January 14, 2019 22:53
Show Gist options
  • Save Bezoar/8569cf70462b62a392cc95dd84ca4374 to your computer and use it in GitHub Desktop.
Save Bezoar/8569cf70462b62a392cc95dd84ca4374 to your computer and use it in GitHub Desktop.
Round robin with multiple iterators
def round_robin_zip(*args):
"""
Make an iterator that aggregates elements from each of the iterables.
If the iterables are of uneven length, shorter iterables are re-iterated.
Iteration continues until the longest iterable is exhausted.
Derived from itertools.zip_longest().
"""
iterators = [iter(it) for it in args]
orig_iterators = set(iterators)
while len(orig_iterators) > 0:
values = []
for i, it in enumerate(iterators):
try:
value = next(it)
except StopIteration:
# Remove old iterator from the original set
if it in orig_iterators:
orig_iterators.remove(it)
# Repeat shorter sequences across the longest one
it = iter(args[i])
iterators[i] = it
value = next(it)
values.append(value)
if len(orig_iterators) > 0:
yield tuple(values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment