简体   繁体   English

从数组1的第一个元素,数组2的第一个元素,数组1的第二个元素,数组2的第二个元素等创建python数组

[英]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. 我创建了单独的向量x,y,vx,vy,它们给出了每个粒子的变量值。 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)? 有没有一种很好的方法将它们自动组合为一个数组,该数组包含粒子1的所有信息,然后包含粒子2的所有信息,等等)? 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)) . 如果您使用的是Python 3,则需要使用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. 这样,您可以按名称引用字段(即c[1].x ,这可以使后续代码和计算更易读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM