Appending to an array in a loop - Python

2019-05-23 04:26发布

问题:

Please see this question for streamlined version with no clutter

I am writing a gravity simulation. The structure of my code is:

  • A solution array - this contains the (already computed) solution for the system of masses. Because of the nature of solving differential equations in Python, all the relevant values (each component of position and velocity for every mass at every time value) are in a the solution array.

  • An array masses. The objects here contain all the information about every mass including the arrays x_historywhich I am trying to update below.

  • No. of dimensions d. Here I have used 2 for simplicity.

I have the following code:

d = 2
for i in range(len(masses)): #  loop through masses
    for k in range(len(solution)): # loop through solution to obtain values at each timestep
        x = []  #  d dimensional x vector at current timestep
        #  fill the x-vector
        for j in range(d):
            x.append(solution[k][d * i + j])
        masses[i].x_history.append(x)

The idea is simply to loop through the objects in the masses array, abstract the relevant information from another array (x arrays representing vectors), and add it to the x_history arrays in the mass objects. The problem is (I have checked this by debugging) in the lines:

masses[i].x_history.append(x)

Rather than appending to masses[i].x_history for the current value of i, the code appends it to the x_history array for all the objects in the masses list, meaning that at the end of the outer loop every object in the masses list contains all the information rather than only its own.

Does anyone have any idea as to why this might be the case? Am I accidentally vectorizing this operation or something?

回答1:

Seems you made the loop correct but appending the value to self.masses[i].x_history at wrong indented position. You have to move that last two line statements one intended (four space) back.