Last active
August 29, 2015 13:57
-
-
Save technige/9358439 to your computer and use it in GitHub Desktop.
Python 2 and 3 compatible round_robin function
This file contains 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
from itertools import cycle, islice | |
def round_robin(*iterables): | |
""" Cycle through a number of iterables, returning | |
the next item from each in turn. | |
round_robin('ABC', 'D', 'EF') --> A D E B F C | |
Original recipe credited to George Sakkis | |
Python 2/3 cross-compatibility tweak by Nigel Small | |
""" | |
pending = len(iterables) | |
nexts = cycle(iter(it) for it in iterables) | |
while pending: | |
try: | |
for n in nexts: | |
yield next(n) | |
except StopIteration: | |
pending -= 1 | |
nexts = cycle(islice(nexts, pending)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment