Python split string in moving window

后端 未结 4 2239
天涯浪人
天涯浪人 2020-12-03 11:39

I have a string with digits like so - digit = \"7316717\"

Now I want to split the string in such a way that the output is a moving window of 3 digits at

4条回答
  •  鱼传尺愫
    2020-12-03 12:21

    There is a very good recipe pairwise in itertools docs.

    Modernizing it a bit for n elements in the group, I made this code:

    from itertools import tee, izip
    
    def window(iterable, n):
        els = tee(iterable, n)
        for i, el in enumerate(els):
            for _ in xrange(i):
                next(el, None)
        return izip(*els)
    
    
    print(["".join(i) for i in window("2316515618", 3)])
    

    Python 2.7

提交回复
热议问题