如何使用函数的最后一个返回值作为循环中同一函数的输入。 Python
How to use the last returned value by a function, as an input for the same function in a loop. Python
我在使用函数的最后一个返回值作为同一函数的输入时遇到问题,我不知道是否可行。
比如我有如下函数:
def sample (x):
p=1+x
return p
sample(h)
并且我想在循环中使用最后返回的值“p”作为 h 的新数据,新函数将如下所示:
def sample (x):
p=1+x
return p
sample(h)
for i in range (0,5):
h=sample(h)
该代码适用于迭代 1 和 2,但不更新迭代 3、4、5 的值。我的真实代码中的变量“p”从其他函数或数据库中获取值并发生变化(它也是一个 3d 数组),因此它会随着每次迭代而变化。第一个输入数据“h”也来自前一个函数。
输入和输出如下:
h= [[[1.71, 1.8, 1.32, 1.56, 2.81], [1., 2., 1., 2., 1.]],
[[1.44, 1.47, 1.5, 1.02, 2.51], [1., 2., 1., 2., 1.]]]
p= [[[1.62, 1.15, 1.1, 1.05, 2.28], [1., 2., 1., 2., 1.]],
[[1.97, 1.85, 1.88, 1.03, 1.87], [1., 2., 1., 2., 2.]]]
如果您能提供帮助,我将不胜感激。 BR.
last_value = None
def sample (x):
p=1+x
last_value = p
return p
sample(last_value)
for i in range (0,5):
h=sample(last_value )
从你的描述中有点难以理解,但我相信这可能会给你想要的结果:
def sample(x):
p = 1+x
return p
h = 1 # Set the initial value here
for i in range(0, 5):
newH = sample(h)
h = newH
print(h) # Remove this print statement if you do not wish the result printed
我在使用函数的最后一个返回值作为同一函数的输入时遇到问题,我不知道是否可行。
比如我有如下函数:
def sample (x):
p=1+x
return p
sample(h)
并且我想在循环中使用最后返回的值“p”作为 h 的新数据,新函数将如下所示:
def sample (x):
p=1+x
return p
sample(h)
for i in range (0,5):
h=sample(h)
该代码适用于迭代 1 和 2,但不更新迭代 3、4、5 的值。我的真实代码中的变量“p”从其他函数或数据库中获取值并发生变化(它也是一个 3d 数组),因此它会随着每次迭代而变化。第一个输入数据“h”也来自前一个函数。
输入和输出如下:
h= [[[1.71, 1.8, 1.32, 1.56, 2.81], [1., 2., 1., 2., 1.]],
[[1.44, 1.47, 1.5, 1.02, 2.51], [1., 2., 1., 2., 1.]]]
p= [[[1.62, 1.15, 1.1, 1.05, 2.28], [1., 2., 1., 2., 1.]],
[[1.97, 1.85, 1.88, 1.03, 1.87], [1., 2., 1., 2., 2.]]]
如果您能提供帮助,我将不胜感激。 BR.
last_value = None
def sample (x):
p=1+x
last_value = p
return p
sample(last_value)
for i in range (0,5):
h=sample(last_value )
从你的描述中有点难以理解,但我相信这可能会给你想要的结果:
def sample(x):
p = 1+x
return p
h = 1 # Set the initial value here
for i in range(0, 5):
newH = sample(h)
h = newH
print(h) # Remove this print statement if you do not wish the result printed