Created
September 1, 2020 18:02
-
-
Save jaquinocode/1a4877a4e39a55ad7c6e2e151930dbc3 to your computer and use it in GitHub Desktop.
A normal generator/iterator that additionally keeps track of the previous element in Python. Also includes an iterator to keep track of next (after) element as well.
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
from itertools import tee, chain | |
# ABC -> (None, A) (A, B) (B, C) | |
def prev_curr_iter(iterable): | |
a, b = tee(iterable) | |
return zip(chain([None], a), b) | |
# use case | |
for prev, curr in prev_curr_iter("ABC"): | |
print(f"{prev=}\t{curr=}") | |
# ------------- | |
# ABC -> (None, A, B) (A, B, C) (B, C, None) | |
def prev_curr_after_iter(iterable): | |
a, b, c = tee(iterable, 3) | |
next(c, None) | |
return zip(chain([None], a), b, chain(c, [None])) | |
# use case | |
for prev, curr, after in prev_curr_after_iter("ABCDEFG"): | |
print(f"{prev=}\t{curr=}\t{after=}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment