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
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]
However , I would recommend just "naming" the tuples instead:
from collections import namedtuple
Particle = namedtuple('Particle', 'x, y, vx, vy')
c = [Particle._make(group) for group in zip(x, y, vx, vy)]
print(c)
Output:
[Particle(x=0, y=3, vx=6, vy=9),
Particle(x=1, y=4, vx=7, vy=10),
Particle(x=2, y=5, vx=8, vy=11)]
That way you can reference the fields by name — ie c[1].x
— which could make subsequent code and calculations a lot more readable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.