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

问题描述 投票:0回答:1

是否可以使用

terraform
来计算列表的累积和?有
sum
函数,但我正在寻找累积和。

示例:

locals {
  numbers_list = [1, 2, 3, 4, 5]
}

期望的输出是:

[1, 3, 6, 10, 15]


等效的

python
代码为:

from numpy import cumsum

print(cumsum([1, 2, 3, 4, 5]))

它打印:

[ 1  3  6 10 15]

terraform
1个回答
0
投票

您可以使用 rangeslice 函数的组合来获得所需的结果:

  • range(max)
    :使用起始值生成数字列表(从
    0
    max - 1
  • slice
    :从列表中提取一些连续元素

示例:

locals {
  values  = [1, 2, 3, 4, 5]
  indexes = range(length(local.values)) # [0, 1, 2, 3, 4]

  cumulative_sum_list = [
    for i in local.indexes :
    # For each index, sum the numbers from the start of the list to the current index
    sum(slice(local.values, 0, i + 1))
  ]
}

output "cumulative_sum_list" {
  value       = local.cumulative_sum_list
  description = "The cumulative sum of the values in the list"
}

跑步

terraform plan

Changes to Outputs:
  + cumulative_sum_list = [
      + 1,
      + 3,
      + 6,
      + 10,
      + 15,
    ]
© www.soinside.com 2019 - 2024. All rights reserved.