【发布时间】:2023-03-28 02:10:01
【问题描述】:
我有这个代码
type key struct {
account string
quantity float64
}
type invoice_tag struct {
account string
value_after_discount float64
value float64
price float64
total_discount float64
discount float64
quantity float64
}
invoice := []invoice_tag{{"Cash", 1024, 1024, 1, 0, 0, 1024}, {"Service Revenue", 0, 2048, 2, 0, 0, 1024}, {"Service Revenue", 0, 0, 0, 1024, 1, 1024}}
m := map[key][5]float64{}
for _, i := range invoice {
m[key{i.account, i.quantity}] = [5]float64{i.value_after_discount, i.value, i.price, i.total_discount, i.discount}
}
fmt.Println(m)
我想按account 和quantity 分组,并将value_after_discount 与value_after_discount 和value 与value 和price 与price 和total_discount 与@987654 和3 相加discount 和 discount。并且输出应该是
map[{Cash 1024}:[1024 1024 1 0 0] {Service Revenue 1024}:[1024 2048 2 1024 1]]
【问题讨论】:
-
@icza 好的,但是如何对多个值求和?
-
总结
a和b和c,你只需写a + b + c。请解释一下你不明白的地方。 -
@icza 我的意思是我想将
a与前一个a和b与前一个b和c与前一个c相加键 -
您将总和存储在地图中,并在下一次迭代中读取该值,添加新值并将新总和存储回地图中。比如:
mymap[key] += value.
标签: dictionary go struct