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

SuperSecretAndHiddenFromWork:

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

这是结构:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章