Created
March 16, 2013 14:07
-
-
Save joshbode/5176540 to your computer and use it in GitHub Desktop.
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 offsetter(iterable, offsets=(0, 1), longest=False): | |
| """ | |
| Return offset element from an iterable. | |
| Pad offset element with None at boundaries. | |
| >>> l = range(10) | |
| >>> for prev, curr, next in offsetter(l, offsets=(-1, 0, 1), longest=True): | |
| ... print prev, curr, next | |
| None 0 1 | |
| 0 1 2 | |
| 1 2 3 | |
| 2 3 4 | |
| 3 4 5 | |
| 4 5 6 | |
| 5 6 7 | |
| 6 7 8 | |
| 7 8 9 | |
| 8 9 None | |
| 9 None None | |
| """ | |
| # clone the iterable | |
| clones = itertools.tee(iterable, len(offsets)) | |
| # set up the clone iterables | |
| iterables = [] | |
| for offset, clone in zip(offsets, clones): | |
| if offset > 0: | |
| # fast forward the start | |
| clone = itertools.islice(clone, offset, None) | |
| elif offset < 0: | |
| # pad the front of the iterable | |
| clone = itertools.chain(itertools.repeat(None, -offset), clone) | |
| else: | |
| # nothing to do | |
| pass | |
| iterables.append(clone) | |
| if longest: | |
| return itertools.izip_longest(*iterables) | |
| else: | |
| return itertools.izip(*iterables) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment