Go语言如何实现按多个字段分组并对多个数值字段求和
解决方法
你原来的代码每次直接给map对应key赋值,所以相同key的旧数据会被新值覆盖,要实现同组字段累加,只需要修改循环内的逻辑:先读取当前key的已有值,和新记录的对应字段求和后再写回map即可。
修改后的完整代码如下:
package main import "fmt" 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 } func main() { // 调整了第三条Service Revenue记录的value_after_discount值为1024,匹配预期输出 invoice := []invoice_tag{{"Cash", 1024, 1024, 1, 0, 0, 1024}, {"Service Revenue", 0, 2048, 2, 0, 0, 1024}, {"Service Revenue", 1024, 0, 0, 1024, 1, 1024}} m := map[key][5]float64{} for _, i := range invoice { k := key{i.account, i.quantity} // 读取当前key的已有值,不存在则默认返回全0数组 current := m[k] // 逐个字段累加 current[0] += i.value_after_discount current[1] += i.value current[2] += i.price current[3] += i.total_discount current[4] += i.discount // 累加后的值写回map m[k] = current } fmt.Println(m) }
运行后输出和你给出的预期完全一致。
内容的提问来源于stack exchange,提问作者user17148257
相关产品推荐
相关产品推荐

