Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用上一次迭代的输出作为新迭代的输入?_Python 3.x_Loops_For Loop_Iteration - Fatal编程技术网

Python 3.x 如何使用上一次迭代的输出作为新迭代的输入?

Python 3.x 如何使用上一次迭代的输出作为新迭代的输入?,python-3.x,loops,for-loop,iteration,Python 3.x,Loops,For Loop,Iteration,我只想运行一个简单的代码,使用上一次迭代的输出作为最新迭代的输入。我有点想这样 a_1 = 2 a_2 = 3 * (a_(n-1)) a_2 = 6 下面包含的代码正是我想要的,并没有反映出我认为实际代码应该是什么样子 import numpy as np Nloop = 10 cList = np.zeros(Nloop) a_1 = 2 #Setting my inital value cList[0] = a_1 for y in range(Nloop): a =

我只想运行一个简单的代码,使用上一次迭代的输出作为最新迭代的输入。我有点想这样

a_1 = 2
a_2 = 3 * (a_(n-1))
a_2 = 6 
下面包含的代码正是我想要的,并没有反映出我认为实际代码应该是什么样子

import numpy as np

Nloop = 10
cList = np.zeros(Nloop)

a_1  = 2  #Setting my inital value
cList[0] = a_1

for y in range(Nloop):
    a = cList[y-1]  # I know this isn't right, but for this I just
                    # want to get the output from the last iteration
    a_n = a * 3
    cList[y] = a_n
我希望结果如下所示:

print(cList)
[2, 6, 18, 54, 162, 486, 1458, 4374, 13122, 36366] 

如有任何指示/帮助/提示,将不胜感激。如果您需要更多信息,请告诉我。

您的代码是正确的。通过进行以下更改,只需从
1
而不是
0
启动
y

for y in range(1, Nloop):
作为旁注,您的整个程序可以重写为:

>>> print([2 * (3 ** i) for i in range(10)])
[2, 6, 18, 54, 162, 486, 1458, 4374, 13122, 39366]

你的代码是正确的。通过进行以下更改,只需从
1
而不是
0
启动
y

for y in range(1, Nloop):
作为旁注,您的整个程序可以重写为:

>>> print([2 * (3 ** i) for i in range(10)])
[2, 6, 18, 54, 162, 486, 1458, 4374, 13122, 39366]