Sometimes I want to use a FIFO-like array by turning a for statement. It seems that there is a queue in Python, but since I am dealing with Javascript, MATLAB, Objective-C, Java, etc. at the same time, I definitely want to write with the same code.
This time I got really into Python. I don't think pop and append are bad, but maybe some people will implement it using pop and append as well, so make a note.
What I wanted to do this time was to get an array that is shifted by one character from the array that is arranged like [1,2,3,4,5,6,7,8,9,10], and the following Make a matrix like this.
So, this time I wrote it in Python, and this is the code that fits nicely. (This code is simplified and there is no problem if you do not write it like this, but the original code had to be written like this)
data_array=[1,2,3,4,5,6,7,8,9,10]
A=[]
R=[]
for i in range(10):
if(len(A)<5):
A.append(data_array[i])
else:
R.append(A)
A.pop(0)
A.append(data_array[i])
The idea is that the first 5 characters should be append normally, and after that, pop and append should be used to create a FIFO-like array and add it.
However, the result is miserably below.
Hmm! ?? You're popping properly, right? Append, right? ?? what! ?? I was tempered with that feeling, but I made a rudimentary mistake that I should be careful about in Python. You have to be careful about the memory of the array.
The details are introduced in detail here. http://qiita.com/utgwkk/items/5ad2527f19150ae33322
And here is the correct code. It seems that you have to move it to another memory with copy.deepcopy
.
import copy
data_array=[1,2,3,4,5,6,7,8,9,10]
A=[]
R=[]
for i in range(10):
if(len(A)<5):
A.append(data_array[i])
else:
temp_data = copy.deepcopy(A)
R.append(temp_data)
A.pop(0)
A.append(data_array[i])
Recommended Posts