我希望模式的长度与数据段的长度相匹配,哪里出错?
data_segment = [] #an empty list
data_series = [-1, 2, -2, 3, 41, 38, 22, 10, -1, 3]
pattern = [40, 30, 20, 10]
out_list = [] #an empty list to contain the final output
length = len(pattern) #length of pattern list
for i, v in enumerate(data_series):
if i + length > len(data_series) + 2:
break
data_segment.append([v, data_series[i+1]])
print(data_segment)
打印
[[-1, 2], [2, -2], [-2, 3], [3, 41], [41, 38], [38, 22], [22, 10], [10, -1], [-1, 3]]
但是我需要它来打印
[[-1, 2, -2, 3], [2, -2, 3, 41], [-2, 3, 41, 38], [3, 41, 38, 22], [41, 38, 22, 10], [38, 22, 10, -1], [22, 10, -1, 3]]
答案 0 :(得分:3)
你的代码
data_segment.append([v, data_series[i+1]])
正在创建一个包含2个元素列表的列表。不是你想要的输出所需要的。
你需要生成一个模式长度的重叠切片列表,并使用一些截断来生成精确模式长度的子列表,在一行中使用列表推导而不是循环:
data_segment = [data_series[i:i+len(pattern)] for i in range((len(data_series)//4)*4 - 1)]
打印:
[[-1, 2, -2, 3], [2, -2, 3, 41], [-2, 3, 41, 38], [3, 41, 38, 22], [41, 38, 22, 10], [38, 22, 10, -1], [22, 10, -1, 3]]