【问题标题】:My For loop is only going through once. (I'm using Python)我的 For 循环只经过一次。 (我正在使用 Python)
【发布时间】:2020-08-06 05:09:10
【问题描述】:

我正在使用 Python,我有一个如下所示的 for 循环。

def calculateTrajectories(masses, positions, velocities, T, dt):

    #create lists for where we want to know positions, velocities at some time and convert them to np arrays
    current_positions = []
    new_positions = np.array(current_positions)
    current_velocities = []
    new_velocities = np.array(current_velocities)

    #call updateParticles function to get new positions, velocities at each step
        #loop starts at 0, ends at T, has step value of dt
    for i in range(0, int(T), int(dt)):
        #show all the time steps in the total time range
        steps = np.array(i)

        #call updateParticles
        Positions, Velocities = updateParticles(masses, positions, velocities, dt)[i]

        #assign the position and velocity results to their respective lists to get turned into arrays
        current_positions.append(Positions)
        current_velocities.append(Velocities)

        return steps, current_positions, current_velocities

    return steps, new_positions, new_velocities

我正在尝试将此函数与 for 循环一起使用来执行此计算,该计算应该产生 3 个名为的数组,steps,new_positions,new_velocities。

T4 = 8.64e7
dt4 = 8640
masses = [1.989e30, 5.972e24]
positions = [(-448794, 0.0, 0.0),(1.4959742e11, 0.0, 0.0)]
velocities = [(0.0, -8.94e02, 0.0),(0.0, 2.98e4, 0.0)]

calculation4 = calculateTrajectories(masses, positions, velocities, T4, dt4)
print(calculation4)

这就是我从中得到的。

(0, [array([ -448793.33565708, -7724160.        ,        0.        ])], [array([1.49597199e+11, 2.57472000e+08, 0.00000000e+00])])

updateParticles 是另一个函数,但我已经检查过,问题与此无关,它肯定与我在这里尝试创建的名为 calculateTrajectories 的函数有关。我不明白为什么我的循环只经历一次,当我给它一系列值时。 此外,在 for 循环的 range() 中,我必须使用 int() 将停止值和步长值设为整数,因为如果我离开它们会出现类型错误,因为浮点数不能被解释为整数。

我怎样才能修复我的循环,使其通过范围函数要求的次数? 感谢您的帮助。

【问题讨论】:

  • 您有 return 在循环内。在第一次迭代后从函数返回。
  • 马克迈耶是正确的。从内部循环中删除 return 并检查代码的输出。可能您将循环的内容添加到另一个变量中,并且该变量将是您将从函数返回的变量

标签: python function for-loop


【解决方案1】:

由于您在for 循环中包含return,因此您定义的函数将在第一次完成。

您可能想要完全删除 return,并将 new_positionsnew_velocities 移到循环下方。

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2015-06-09
    • 2019-04-06
    • 1970-01-01
    • 2017-09-12
    • 2016-01-09
    • 2021-06-15
    相关资源
    最近更新 更多