Created
July 15, 2015 11:37
-
-
Save Mause/8f09062debae85a480d5 to your computer and use it in GitHub Desktop.
Efficient, lazy, iterator, python pairing
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 chain, tee | |
def pairs(iterator): | |
""" | |
Returns the items in the iterator pairwise, like so; | |
>>> list(pairs([0, 1, 2])) | |
[(0, 1), (1, 2)] | |
""" | |
first, second = tee(iterator) | |
ret = zip(chain([None], second), first) | |
# this is a generator so that execution doesn't begin until the user | |
# starts consuming us, and so that we then don't start consuming our | |
# iterator until they ask us to | |
next(ret) # kill the first half-empty pair | |
yield from ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment