本文介绍了使用Python 2.7.1中的itertools,yield和iter()生成带有滑动窗口的字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Python中生成一个滑动窗口函数.我想出了如何做到这一点,但并非所有功能都在其中. itertools,yield和iter()对我来说是全新的.
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.
我想输入
a='abcdefg'
b=window(a,3)
print b
['abc','bcd','cde','def','efg']
我工作的方式是
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?
这是我的函数代码
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
我希望它返回加入的列表,但是当我按下运行它时,它说:您的程序 * 'return'并在生成器内部带有参数时出错"
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 . . .
推荐答案
您是说要这样做? :
a='abcdefg'
b = [a[i:i+3] for i in xrange(len(a)-2)]
print b
['abc', 'bcd', 'cde', 'def', 'efg']
这篇关于使用Python 2.7.1中的itertools,yield和iter()生成带有滑动窗口的字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!