You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将矩阵存入字典并迭代添加新矩阵至文件?

问题解决与优化方案

报错原因

你调用append的对象是numpy数组,而append是Python列表的专属方法,numpy数组没有这个属性,因此触发AttributeError。

修正方案

方案1:用列表存储迭代结果(简单直观)

初始化时把字典里的Fitness和Population设为空列表,每次迭代将新的numpy数组追加进去:

# 初始化结果容器:用列表存放每次迭代的数组
Results_trainPSO_Firestation = [{'Fitness': [], 'Population': []}]

# 先存入初始的CurrentPop数据
Results_trainPSO_Firestation[0]['Fitness'].append(CurrentPop[:, n_par])
Results_trainPSO_Firestation[0]['Population'].append(CurrentPop[:, :n_par])

# 执行50次迭代
for _ in range(50):
    # 这里写你的CurrentPop更新逻辑
    # ...
    
    # 添加当前迭代的结果到列表
    Results_trainPSO_Firestation[0]['Fitness'].append(CurrentPop[:, n_par])
    Results_trainPSO_Firestation[0]['Population'].append(CurrentPop[:, :n_par])

# 统一保存(建议用.npy格式,比.txt更适合numpy数据存储)
np.save('Results_trainPSO_Firestation.npy', Results_trainPSO_Firestation)

读取时直接用np.load('Results_trainPSO_Firestation.npy')即可恢复数据。

方案2:预分配numpy数组(高效,适合大迭代次数)

如果已知总共有51次结果(初始状态+50次迭代),可以预分配固定形状的numpy数组,避免列表追加的开销,效率更高:

total_rounds = 50 + 1  # 初始状态+50次迭代

# 预分配数组形状:Fitness是(51,10),Population是(51,10,6)(假设CurrentPop是10×6)
fitness_arr = np.empty((total_rounds, *CurrentPop[:, n_par].shape))
population_arr = np.empty((total_rounds, *CurrentPop[:, :n_par].shape))

# 存入初始数据
fitness_arr[0] = CurrentPop[:, n_par]
population_arr[0] = CurrentPop[:, :n_par]

# 迭代循环
for i in range(1, total_rounds):
    # 更新CurrentPop
    # ...
    
    # 存入第i次迭代的结果
    fitness_arr[i] = CurrentPop[:, n_par]
    population_arr[i] = CurrentPop[:, :n_par]

# 组织成字典并保存
Results_trainPSO_Firestation = [{'Fitness': fitness_arr, 'Population': population_arr}]
np.save('Results_trainPSO_Firestation.npy', Results_trainPSO_Firestation)

关于字典是否为最优方案

用字典组织Fitness和Population是非常合理的选择——它能清晰区分两类数据结构,后续如果需要添加其他迭代相关数据(比如迭代耗时、全局最优值等),直接在字典中新增键值对即可,灵活性强。

内容的提问来源于stack exchange,提问作者João Sousa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 01:29:59