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

天涯浪子 提交于 2019-11-30 22:15:59

You mean you want to do this ? :

a='abcdefg'
b = [a[i:i+3] for i in xrange(len(a)-2)]
print b
['abc', 'bcd', 'cde', 'def', 'efg']

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

Use zip function in one line code:

  [ "".join(j) for j in zip(*[fseq[i:] for i in range(window_size)])]
def window(fseq,fn):
    alpha=[fseq[i:i+fn] for i in range(len(fseq)-(fn-1))]
    return alpha

I don't know what your input or expected output are, but you cannot mix yield and return in one function. change return to yield and your function will not throw that error again.

def window(fseq, window_size=5):
    ....
        final.append(tentative_string)
    yield final
>>>def window(data, win_size):
...    tmp = [iter(data[i:]) for i in range(win_size)]
...    return zip(*tmp)
>>> a = [1, 2, 3, 4, 5, 6]
>>> window(a, 3)
>>>[(1,2,3), (2,3,4), (3,4,5), (4,5,6)]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!