【问题标题】:How can I use the output from a previous iteration as the input for a new iteration?如何使用上一次迭代的输出作为新迭代的输入?
【发布时间】:2020-02-18 02:59:12
【问题描述】:

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

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] 

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

【问题讨论】:

    标签: python-3.x loops for-loop iteration


    【解决方案1】:

    您的代码是正确的。只需进行以下更改,即可从 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]
    

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 2014-06-30
      • 2014-03-20
      相关资源
      最近更新 更多