Python中如何将for循环的输出结果全部追加到列表中?
解决Lotka-Volterra模型循环中无法保存所有diff值的问题
你遇到的问题核心是列表初始化位置错误:你把diffList = []写在了for循环内部,每次循环迭代时都会重新创建一个空列表,之前计算的diff值会被直接丢弃,最后自然只保留了最后一次循环的结果。
解决方案
把diffList = []移到for循环外面,让列表只初始化一次,之后每次循环都往同一个列表里追加diff值。同时还可以优化一些重复定义的代码,提升运行效率:
# Question 1 import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint from scipy.interpolate import CubicSpline from numpy import log # 提前定义sim函数,避免循环内重复定义 def sim(variables, t, params): # Prey population level x = variables[0] # Predator population level y = variables[1] alpha = params[0] beta = params[1] delta = params[2] gamma = params[3] dxdt = alpha * x - beta * x * y dydt = delta * x * y - gamma * y return [dxdt, dydt] y0 = [10,1] # [Prey, Predator] units in hundreds pd = [100,200,300,400,500,600,700,800,900,1000, 1100, 1200, 1300,1400,1500,1600,1700,1800,1900,2000] # 列表初始化移到循环外,只创建一次 diffList = [] # 模型参数提前定义,无需每次循环重复赋值 alpha = 0.1 beta = 0.02 gamma = 0.4 delta = 0.02 params = [alpha, beta, delta, gamma] for x in pd: t = np.linspace(0.,50.,num=x) y = odeint(sim, y0, t, args=(params,)) lv_prey = y[:,0] # 单独保存猎物种群数据 lv_pred = y[:,1] # 单独保存捕食者种群数据 prey_array = np.array(lv_prey) pred_array = np.array(lv_pred) # 拟合三次样条 num_pts = 10 tsp = np.array([t[i] for i in range(0, len(t), len(t)//num_pts)]) # 猎物样条拟合 prey_sp = np.array([lv_prey[i] for i in range(0, len(t), len(t)//num_pts)]) Curve1 = CubicSpline(tsp, prey_sp, bc_type = 'natural', extrapolate = False) # 捕食者样条拟合 pred_sp = np.array([lv_pred[i] for i in range(0, len(t), len(t)//num_pts)]) Curve2 = CubicSpline(tsp, pred_sp, bc_type='natural', extrapolate=False) prey_extrap_dots=Curve1(tsp) prey_extrap_line = Curve1(np.array([tt for tt in t if tt<=tsp[-1]])) pred_extrap_dots=Curve2(tsp) pred_extrap_line=Curve2(np.array([tt for tt in t if tt<=tsp[-1]])) # 计算Lotka-Volterra模型的不变量差值 Cspline = alpha*np.log(pred_extrap_line) - beta*(pred_extrap_line) - delta*(prey_extrap_line) + gamma*np.log(prey_extrap_line) diff = np.max(Cspline) - np.min(Cspline) diffList.append(diff) print("The difference is {}".format(diff)) # 现在diffList包含所有循环计算的diff值 print("All calculated differences:", diffList)
额外优化说明
除了修复列表初始化问题,还做了两处实用优化:
- 将
sim函数移到循环外,避免每次循环重复定义同一个函数,减少不必要的性能开销 - 把固定不变的模型参数(alpha、beta等)移到循环外定义,避免重复赋值
内容的提问来源于stack exchange,提问作者s_o_c_account
相关产品推荐
相关产品推荐

