Created
June 18, 2013 12:40
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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