是否可以使用
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]
您可以使用 range 和 slice 函数的组合来获得所需的结果:
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,
]