登录
首页 >  Golang >  Go问答

按键对映射进行分类,并计算数组的值之和

来源:stackoverflow

时间:2024-03-14 10:33:25 403浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《按键对映射进行分类,并计算数组的值之和》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我有一个结构数组,是通过获取句子列表的词频计数来构建的。其输出是每句话最流行的单词。我需要在所有句子中使用它

以下是结构:

type wordcountstruct struct {
    word string
    freq int
}

type wordcountstructarray []wordcountstruct

这是 wordcountstructarray 的示例:

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

这就是每个句子的最常见单词的有序列表。 我需要按键分组,并对值求和

对于上面的 5 个样本集,这将导致:

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

我可以将结构转换为 []map[string]interface{} 如果这样更容易的话?


解决方案


您正在寻找这样的东西吗?

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

以上就是《按键对映射进行分类,并计算数组的值之和》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>