drf16571 2019-06-10 09:34
浏览 74
已采纳

按键对地图/结构进行分组,然后对数组的关联值求和

I have an array of structs that i've built by getting a word frequency count for a list of sentences. The output from this is the most popular words per sentence. I need it across all sentences

Here are the structs:

type WordCountStruct struct {
    word string
    freq int
}

type WordCountStructArray []WordCountStruct

This is a sample of the WordCountStructArray:

[{the 8} {and 8} {to 7} {and 6} {and 6}]

So what this is is an ordered list, for each sentence, of the most common words. I need to group by the key, and sum the values

In the case of the 5 sample set above, this would result in:

[{the 8} {to 7} {and 20}]

I can convert the struct to a []map[string]interface{} if this is easier?

  • 写回答

1条回答 默认 最新

  • doushi3454 2019-06-10 11:43
    关注

    Is something like this what your looking for?

    package main
    
    import "fmt"
    
    type WordCountStruct struct {
        word string
        freq int
    }
    
    type WordCountStructArray []WordCountStruct
    
    func main() {
        wCounts := WordCountStructArray{
            WordCountStruct{"the", 8},
            WordCountStruct{"and", 8},
            WordCountStruct{"to", 7},
            WordCountStruct{"and", 6},
            WordCountStruct{"and", 6},
        }
    
        fmt.Println(wCounts)
    
        freq := make(map[string]int)
        for _, wCount := range wCounts {
            freq[wCount.word] += wCount.freq
        }
    
        fmt.Println(freq)
    }
    

    https://play.golang.org/p/oCqfoCy_W2g

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料