Last active
December 9, 2023 18:41
-
-
Save nathan-cruz77/2568ae0293b9685b75fa803e850fb3d9 to your computer and use it in GitHub Desktop.
Sliding window for iterables.
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 islice | |
# Slides through iterable each `n` elements. | |
# | |
# Sample usage: | |
# | |
# >>> list(sliding_window([1, 2, 3, 4])) | |
# [(1, 2), (2, 3), (3, 4)] | |
# | |
# >>> list(sliding_window([1, 2, 3])) | |
# [(1, 2), (2, 3)] | |
# | |
# >>> list(sliding_window([1, 2, 3, 4], n=3)) | |
# [(1, 2, 3), (2, 3, 4)] | |
# | |
def sliding_window(iterable, n=2): | |
args = [islice(iter(iterable), i, None) for i in range(n)] | |
return zip(*args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment