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 . . .
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)]
来源:https://stackoverflow.com/questions/8408117/generate-a-list-of-strings-with-a-sliding-window-using-itertools-yield-and-ite