Generate a list of strings with a sliding window using itertools, yield, and iter() in Python 2.7.1?

后端 未结 6 1016
鱼传尺愫
鱼传尺愫 2020-12-18 03:21

I\'m trying to generate a sliding window function in Python. I figured out how to do it but not all inside the function. itertools, yield, and iter() are entirely new to me

6条回答
  •  被撕碎了的回忆
    2020-12-18 04:19

    Your generator could be much shorter:

    def window(fseq, window_size=5):
        for i in xrange(len(fseq) - window_size + 1):
            yield fseq[i:i+window_size]
    
    
    for seq in window('abcdefghij', 3):
        print seq
    
    
    abc
    bcd
    cde
    def
    efg
    fgh
    ghi
    hij
    

提交回复
热议问题