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

时间:2019-06-10 09:34:52

标签: arrays go maps aggregate

我通过获取句子列表的词频计数构建了一系列结构。此输出是每个句子中最受欢迎的单词。我在所有句子中都需要它

以下是结构:

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 {}吗?

1 个答案:

答案 0 :(得分:3)

您想要的是这样的东西吗?

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