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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:15:01