Python – Why am I only half the length I want?

Why am I only half the length I want?… here is a solution to the problem.

Why am I only half the length I want?

I want the length of the schema to match the length of the data segment, what went wrong?

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)

Which prints

[[-1, 2], [2, -2], [-2, 3], [3, 41], [41, 38], [38, 22], [22, 10], [10, -1], [-1, 3]]

But I need it to print

[[-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]]

Solution

Your code

data_segment.append([v, data_series[i+1]])

Creating a list of 2-element lists. Not what you want for the output you want.

You need to generate a list with overlapping slices of pattern length, with some truncation to produce only sublists of exact pattern lengths, using list understanding instead of looping in one row:

data_segment = [data_series[i:i+len(pattern)] for i in range((len(data_series)//4)*4 - 1)]

Print:

[[-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]]

Related Problems and Solutions