从for循环中重用for循环中的变量

时间:2018-10-02 10:16:20

标签: python loops for-loop

    for x in range(len(Bodies):
        planet = Bodies[x]
        if planet == planetinit:
            expression

        else:

            fx = -gravconst*rx/r3
            templistx.append(fx)
            forcex = sum(templistx)
            templistx.clear()
    vx += (forcex/Bodies[n].M)*dt

我想在循环外使用forcex,但这是不可能的,并且出现错误: NameError:名称“ forcex”未定义

1 个答案:

答案 0 :(得分:3)

您应将循环之前的列表定义为空列表。

Dimensions:    (bnds: 2, lat: 15, lon: 13, time: 122)
Coordinates:
  * time       (time) float64 15.0 45.0 75.0 ... 3.585e+03 3.615e+03 3.645e+03
  * lat        (lat) float64 -42.5 -40.0 -37.5 -35.0 ... -15.0 -12.5 -10.0 -7.5
  * lon        (lon) float64 112.5 116.2 120.0 123.8 ... 146.2 150.0 153.8 157.5

Dimensions without coordinates: bnds
Data variables:
    time_bnds  (time, bnds) float64 ...
    lat_bnds   (lat, bnds) float64 ...
    lon_bnds   (lon, bnds) float64 ...
    pr         (time, lat, lon) float32 ...

希望这会有所帮助。