Generate a list of strings with a sliding window u

2020-03-04 12:14发布

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.

i want to input

a='abcdefg'
b=window(a,3)
print b
['abc','bcd','cde','def','efg']

the way i got it work was

def window(fseq, window_size=5):
    import itertools
    tentative=[]
    final=[]
    iteration=iter(fseq)
    value=tuple(itertools.islice(iteration,window_size))
    if len(value) == window_size:
        yield value
    for element in iteration:
        value = value[1:] + (element,)
        yield value

a='abcdefg'
result=window(a)
list1=[]
for k in result:
    list1.append(k)
list2=[]   
for j in list1:
    tentative=''.join(j)
    list2.append(tentative)
print list2

basically what im confused about is how to use the final value of the function inside the function?

here is my code for the function

def window(fseq, window_size=5):
    import itertools
    tentative=[]
    final=[]
    iteration=iter(fseq)
    value=tuple(itertools.islice(iteration,window_size))
    if len(value) == window_size:
        yield value
    for element in iteration:
        value = value[1:] + (element,)
        yield value
    for k in value:
        tentative.append(k)
    for j in tentative:
        tentative_string=''.join(j)
        final.append(tentative_string)
    return final



seq='abcdefg'
uence=window(seq)
print uence

i want it to return the joined list but when i press run it, it says "There's an error in your program * 'return' with argument inside generator"

I'm really confused . . .

6条回答
仙女界的扛把子
2楼-- · 2020-03-04 12:38

Use zip function in one line code:

  [ "".join(j) for j in zip(*[fseq[i:] for i in range(window_size)])]
查看更多
别忘想泡老子
3楼-- · 2020-03-04 12:38
>>>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)]
查看更多
放我归山
4楼-- · 2020-03-04 12:50

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
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-03-04 12:58

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
查看更多
萌系小妹纸
6楼-- · 2020-03-04 13:00

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']
查看更多
Animai°情兽
7楼-- · 2020-03-04 13:01
def window(fseq,fn):
    alpha=[fseq[i:i+fn] for i in range(len(fseq)-(fn-1))]
    return alpha
查看更多
登录 后发表回答