0

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

1 Answer 1

1

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 — i.e. c[1].x — which could make subsequent code and calculations a lot more readable.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, that's what I was getting at. Thanks very much. Will the fact that the new list is grouped (as the brackets indicate) have any effect on any future calculations done on it?
I think it does. Is there any way of doing the same thing without it being a list of tuples? i.e. just the individual numbers in the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.