繁体   English   中英

将列表元组添加到python中的列表

[英]Adding tuples of lists to a list in python

我不明白将元组(其元素也是列表的元素)添加到包含所有信息的另一个列表的语法。

我正在尝试创建一个轨迹列表,其中包含弹丸飞行过程中飞行数据的元组。 我想使用元组,以便我可以及时查看每个时刻的所有信息。

import random
import math

gg = -9.81 # gravity m/s**2
tt = 10 **-9 # seconds
wind = random.randint(-10,10)   # m/s

#position
x=random.randint(0,100)   # m/s

#projectile

v0 = float(raw_input('Enter the initial velocity (m/s) -> '));
theta = float(raw_input('Enter the initial launch angle of projectile (degrees) -> '));

theta *= (180/3.14159265359)

xx = [x]
yy = [.000000000000000000001]
dz =[v0]
time = [0];


data = ( time, xx, yy, dz)
traj = [data]


while yy[-1] >0:

    traj.append ( math.sqrt( (traj[-1][3][-1] * math.sin(theta) + gg * tt)** 2+        (traj[-1][4] * math.cos(theta) -wind) ** 2 ))    # velocity
    traj.append ( traj[-1][2][-1] + dz[-1] * math.sin(theta) * tt + .5* gg * tt)    # y position
    traj.append ( traj[-1][1][-1] * dz[-1] * math.cos(theta) - wind * tt)    # x position
    traj.append ( traj[-1][0][-1] + tt)     # time


print traj

编辑:我将输入整数作为初始角度和速度(即-45,45)。 预期的输出将是一个元组列表,其中包含分别对应于时间,x坐标,y坐标和速度的四个元素。 目前,我收到一个元组索引超出范围错误。

你在哪里

traj[-1][4]

在您的第一条traj.append行中, traj[-1]data ,并且data只有四个元素长,因此最后一项在索引3处。

代码的问题是,您将数据添加到while循环中的计算值添加到traj列表。 这不会更新列表xxyytimedz 您可以通过以下方式修改代码

while yy[-1] > 0:
    dz_next = math.sqrt( (yy[-1] * math.sin(theta) + gg * tt)** 2+(dz[-1] * math.cos(theta) -wind)** 2)
    yy_next = yy[-1] + dz[-1] * math.sin(theta) * tt + .5* gg * tt
    xx_next = xx[-1] * dz[-1] * math.cos(theta) - wind * tt

    dz.append(dz_next)    # velocity
    yy.append(yy_next)    # y position
    xx.append(xx_next)    # x position
    time.append(time[-1] + tt)     # time

我认为以下是更好的方法

data = ( 0, x, 1e-20, v0) # initial data
traj = [data]

while True:
    t, x, y, v = traj[-1]
    if y < 0:
        break

    traj.append((t + tt, # time
                 x * v * math.cos(theta) - wind * tt, # x position
                 y + v * math.sin(theta) * tt + .5* gg * tt, # y position
                 (y* math.sin(theta) + gg * tt)** 2 + (v*math.cos(theta) -wind) ** 2) # velocity
    )


    print traj
    t_traj, x_traj, y_traj, z_traj = zip(*traj)

暂无
暂无

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

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