Skip to content

Instantly share code, notes, and snippets.

@zvikico
Created June 18, 2013 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zvikico/5805014 to your computer and use it in GitHub Desktop.
Save zvikico/5805014 to your computer and use it in GitHub Desktop.
This function will interleave results from multiple iterators, exhausting all iterators in the process (i.e. ignoring iterators that has no more value).
import itertools
def iter_interleave(*args):
iterators = [(x for x in it) for it in args]
has_values = [True for _ in xrange(len(iterators))]
while max(has_values):
for it, has_value, i in itertools.izip(iterators, has_values, xrange(len(iterators))):
if has_value:
try:
value = it.next()
yield value
except StopIteration:
has_values[i] = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment