I am trying to create a custom function that improves the itertools pairwise function.
Unlike the pairwise function, which returns pairs of items (n=2), I would like to be able to specify the grouping length (n=x). So that I can return groups of items of a specified length. Is this possible?
So when n=2
, the groupwise function should be equivalent to the itertools pairwise function. But when n=3
, I would expect it to return groups of 3.
This is what I have so far - which is essentially the same as the pairwise function. ie. works for n=2.
Code:
from itertools import tee
my_string = 'abcdef'
def groupwise(iterable, n):
a = tee(iterable, n)
next(a[n-1], None)
return zip(a[0], a[1])
for item in groupwise(my_string, 2):
print("".join(item))
Output:
ab
bc
cd
de
ef
I am trying to modify the code above to accept n=3, n=4, n=5, ... n=x
, but I cannot think of a way to provide the undetermined number of components to the zip function considering that I would like to specify any value of n <= len(my_string)
When n=3 the output should be:
abc
bcd
cde
def