【问题标题】:Adding tuples of lists to a list in python将列表元组添加到python中的列表
【发布时间】:2014-09-12 22:54:42
【问题描述】:

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

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

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 坐标和速度。目前,我收到元组索引超出范围错误。

【问题讨论】:

  • 如果您显示以下内容会很有帮助:1. 样本输入 2. 预期输出 3. 实际输出
  • 欢迎来到 S.O.!您应该告诉我们您的输入和输出是什么,以及您的输出与您的预期有何不同。 sscce.org
  • 你的while循环有多个问题,你需要在循环中打印出traj看看哪里出错了
  • 除了这里的其他问题,theta *= (180/3.14159265359) 是错误的,因为它将弧度转换为度数;你想要theta *= 3.14159265359/180,甚至更好,theta = math.radians(theta)

标签: python list tuples


【解决方案1】:

你在哪里

traj[-1][4]

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

【讨论】:

  • 我诊断出我看到的第一个错误,@Padraic。随意为他/她重写整个程序并把一切都做好。
  • 错误太多了,我得重写90%的代码,OP自己调试会学到更多。
  • 我有可能是在讽刺。
  • 既然你有足够的精力去讽刺,而且你已经开始回答这个问题,你不妨自己重写所有代码;)
【解决方案2】:

您的代码的问题是您将在 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2021-12-27
    • 2020-05-12
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多