Search code examples
pythonpython-3.xpython-itertoolsmore-itertools

Python join more_itertools.windowed results


I have a following problem: I am trying to create so-called "digrams", like this:

If I have a word foobar, I want to get a list or a generator like: ["fo", "oo", "ob", "ba", "ar"]. The perfect function to that is more_itertools.windowed. The problem is, it returns tuples, like this:

In [1]: from more_itertools import windowed

In [2]: for i in windowed("foobar", 2):
   ...:     print(i)
   ...:
('f', 'o')
('o', 'o')
('o', 'b')
('b', 'a')
('a', 'r')

Of course I know I can .join() them, so I would have:

In [3]: for i in windowed("foobar", 2):
   ...:     print(''.join(i))
   ...:
   ...:
fo
oo
ob
ba
ar

I was just wondering if there's a function somewhere in itertools or more_itertools that I don't see that does exactly that. Or is there a more "pythonic" way of doing this by hand?


Solution

  • You can write your own version of widowed using slicing.

    def str_widowed(s, n):
        for i in range(len(s) - n + 1):
            yield s[i:i+n]
    

    This ensure the yielded type is the same as the input, but no longer accepts non-indexed iterables.