python - Cummulative addition in a loop
问题描述
I am trying to cummatively add a value to the previous value and each time, store the value in an array.
This code is just part of a larger project. For simplicity i am going to define my variables as follows:
ele_ini = [12]
smb = [2, 5, 7, 8, 9, 10]
val = ele_ini
for i in range(len(smb)):
val += smb[i]
print(val)
elevation_smb.append(val)
Problem
Each time, the previous value stored in elevation_smb
is replaced by the current value such that the result i obtain is:
elevation_smb = [22, 22, 22, 22, 22, 22]
The result i am expecting however is
elevation_smb = [14, 19, 26, 34, 43, 53]
NOTE:
ele_ini
is a vector with n elements. I am only using 1 element just for simplicity.
解决方案
不要使用循环,因为慢。更好的是下面的快速矢量化解决方案。
我认为需要并numpy.cumsum
添加向量ele_ini
:2d numpy array
ele_ini = [12, 10, 1, 0]
smb = [2, 5, 7, 8, 9, 10]
elevation_smb = np.cumsum(np.array(smb)) + np.array(ele_ini)[:, None]
print (elevation_smb)
[[14 19 26 34 43 53]
[12 17 24 32 41 51]
[ 3 8 15 23 32 42]
[ 2 7 14 22 31 41]]
推荐阅读
- next.js - Nextjs 应用程序在开发模式下按预期工作,但当我尝试“npm run build”并出现 Entrymodulenotfound 错误时失败
- netflix-eureka - 命中端点时出现异常:负载均衡器没有可供客户端使用的服务器
- python - 处理和清理非结构化数据
- r - R-pkgs Roxygen \varphi 无法渲染
- powershell - 使用 EXO v2 PS 模块在线连接到 Exchange - 本周开始出现问题
- c++ - c++ 类中的函数指针引发编译器错误
- reactjs - 在 React 项目中使用 Material ui 和 Tailwind css
- linux - 从 USB 设备加载根文件系统
- java - 如何转换 AWS Lambda 为 AWS Batch 创建图像
- javascript - 如何在使用 JavaScript 检测选项卡更改时获取选项卡的标题/URL