如何将Python函数上次运行的输出作为下一次输入重复执行
实现方法
你只需要把现有逻辑封装成函数,循环调用时把上一次的返回值传入下一次调用即可,具体操作如下:
- 先修正原代码的两处问题:一是
SizeSmall行前多了多余缩进,二是只写了bigspeed = vcalc(SizeBig),漏了smallspeed = vcalc(SizeSmall)的计算逻辑,先把这两处补全。 - 将整段运算逻辑封装为入参为
N0Small、N0Big,返回值为num_smallspeed、num_bigspeed的函数 - 设置首次运行的初始
N0Small、N0Big,循环调用函数,每次用返回值替换下一轮的入参即可
参考实现代码如下:
import numpy as np import math # 保留你自己实现的vcalc函数即可,这里仅做占位避免报错 def vcalc(size_arr): # 替换为你自己的vcalc业务逻辑 return np.random.random(size_arr.shape) # 封装单次运行的核心逻辑 def run_single_cycle(N0Small, N0Big, tSmall, tBig, t, meanSmall, sdSmall, meanBig, sdBig): k = np.log(2)/tSmall N24Small = N0Small * math.exp(k*t) k = np.log(2)/tBig N24Big = N0Big * math.exp(k*t) SizeSmall = np.random.normal(meanSmall, sdSmall, int(N24Small)) SizeBig = np.random.normal(meanBig, sdBig, int(N24Big)) # 补全原代码漏写的smallspeed计算逻辑 smallspeed = vcalc(SizeSmall) bigspeed = vcalc(SizeBig) allSpeed = np.concatenate((smallspeed, bigspeed)) allSpeed_hun = allSpeed[0:99] num_smallspeed = len(set(allSpeed_hun).intersection(smallspeed)) num_bigspeed = len(set(allSpeed_hun).intersection(bigspeed)) # 返回两个结果作为下一轮的输入 return num_smallspeed, num_bigspeed # ------------参数配置区,替换为你自己的实际数值------------ # 首次运行的初始N0值 init_N0Small = 100 init_N0Big = 100 # 其他固定参数 tSmall = 10 tBig = 20 t = 24 meanSmall = 5 sdSmall = 1 meanBig = 10 sdBig = 2 # 要循环运行的次数 cycle_count = 10 # 循环运行逻辑 current_N0S, current_N0B = init_N0Small, init_N0B for i in range(cycle_count): current_N0S, current_N0B = run_single_cycle( current_N0S, current_N0B, tSmall, tBig, t, meanSmall, sdSmall, meanBig, sdBig ) # 需要打印每轮结果可以打开下面的注释 # print(f"第{i+1}轮运行结果:num_smallspeed={current_N0S}, num_bigspeed={current_N0B}")
如果你需要一直运行直到满足某个终止条件,把for循环替换为while循环即可,示例:
# 示例:直到两个数值都大于等于200才停止运行 current_N0S, current_N0B = init_N0Small, init_N0B while current_N0S < 200 or current_N0B < 200: current_N0S, current_N0B = run_single_cycle( current_N0S, current_N0B, tSmall, tBig, t, meanSmall, sdSmall, meanBig, sdBig )
内容的提问来源于stack exchange,提问作者Ayan Guha
相关产品推荐
相关产品推荐

