I have a problem with initializing an array in python. I have been trying to search for a solution, however I have not found anything. (It could be that I searched for wrong keywords). Anyways, this is what I am trying to achieve: I am writing a python script for a machine vision application. The application consists of several "tools" that are run iteratively in its ordered sequence. One of these tools I am writing as a python script. In this script I need to create an array type variable, that for each iteration will remove the first value and append a new value at the end. As it needs to remember the array between iterations, does it have to be global? The problem is that I need to define the variable as an array at the beginning of the script. For this, I use: xPosition_array = [] Later in the script, I append a value. However, next iteration xPosition_array = [] will overwrite the array with an empty one. How can I make the code such that the array is defined/initialized only once (first iteration)?
Thanks in advance.
The code:
global xPosition_array
xPosition_array = []
filter_win_len = 40
def moving_average(a, n) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
xPosition = GetValue('LocatexPos.Line[1]_q_x')
if len(xPosition_array) < filter_win_len:
xPosition_array.append(xPosition)
elif len(xPosition_array) == filter_win_len:
xPosition_array.pop(0)
xPosition_array.append(xPosition)
xPosition_filtered = moving_average(xPosition_array, filter_win_len)