Tim Smith Tim Smith - 7 months ago 15
Python Question

Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc

I am attempting to create a state vector representing the positions and velocities of a series of particles at a given time, for a simulation. I have created individual vectors x,y,vx,vy which give the value of that variable for each particle. Is there a good way of automatically combining them into one array, which contains all the info for particle one, followed by all the info for particle two etc etc)? Thanks

Answer

Do you mean like this?

x = [0, 1, 2]
y = [3, 4, 5]
vx = [6, 7, 8]
vy = [9, 10, 11]

c = zip(x, y, vx, vy)
print(c)  # -> [(0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11)]

if you're using Python 3, you would need to use c = list(zip(x, y, vx, vy)).

If you don't want the values for each particle grouped into a tuple like that for some reason, the result could be flattened:

c = [item for group in zip(x, y, vx, vy) for item in group]
print(c)  # -> [0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11]