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

如何在Terraform中计算列表的累积和?

在Terraform中计算列表的累积和

可以实现。虽然Terraform没有直接提供类似Python numpy中cumsum的内置函数,但可以通过结合for循环、slice和sum函数手动实现累积和计算。

示例实现

locals {
  numbers_list = [1, 2, 3, 4, 5]
  cumulative_sum = [
    for i, val in local.numbers_list :
    sum(slice(local.numbers_list, 0, i + 1))
  ]
}

# 输出验证
output "result" {
  value = local.cumulative_sum
}

逻辑说明

  • 遍历目标列表的每个元素及其索引i
  • 用slice函数截取列表从开头到当前索引+1的子列表(索引从0开始,i+1确保包含当前元素)
  • 对每个子列表调用sum函数求和,得到对应位置的累积值

执行后,local.cumulative_sum的值即为期望的[1, 3, 6, 10, 15]。

内容的提问来源于stack exchange,提问作者Adama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:42:03