dictionary - 如何使用 Golang 计算 map 中某个值的出现次数?

标签 dictionary go sum

我创建了一个具有以下结构的 map :

m := make(map[int]Record)

记录是一个结构如下:

type Record struct {
    UID  int
    Type string
    Year string
}

SumRecord 结构应该存储有关映射 m 中每个给定类型/年份值出现次数的信息。

type SumRecord struct {
    Sum  int
    Type string
    Year string
}

该结构应该保存有关书籍出版年份的信息,即 {1, "Type": "fiction", "Year": 1996}, {2, "Type": "non-fiction", “年”:1996}

我试图创建第二个 map 但没有成功,我将在其中存储每年每种出版物类型的总和(类似于 SQL 中的 SUM/GROUP BY)。我如何使用 Go 实现这一目标?

最佳答案

这是@ThunderCat 提供的另一种解决方案。

这会创建一个新的 SumRecord 到整数的映射,表示该特定类型/年份分组的出现次数总和。

查看完整示例 here .

type Record struct {
    UID  int
    Type string
    Year string
}

type SumRecord struct {
    Type string
    Year string
}

m := make(map[int]Record)

// e.g. [{"1996","non-fiction"}:4], representing 4 occurrences of {"1996","non-fiction"}
srMap := make(map[SumRecord]int)

// add records

// loop over records
for key := range m {
    sr := SumRecord{
        Type: m[key].Type,
        Year: m[key].Year,
    }
    // creates new counter or increments existing pair counter by 1
    srMap[sr] += 1
}
// print all mappings
fmt.Println(srMap)

// specific example
fmt.Println(srMap[SumRecord{
    Year: "1996",
    Type: "non-fiction",
}])

关于dictionary - 如何使用 Golang 计算 map 中某个值的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54993543/

相关文章:

c# - 如何模拟字典?

C++ Map基于变量键返回类对象

javascript - 通过 .map 循环创建按钮时出现问题

go - 这个 Go print 语句的顺序是什么?

php - LEFT JOIN 与 SUM 不工作

ios - 使用 arcgis iOS 经度和纬度显示位置结果不正确

sql - 使用golang返回mysql过程

regex - 重写正则表达式而不使用否定

c++ - 如何在 C++ 中使用 Hashmap 查找任意随机数组中总和为特定值的所有对

sum - 如果有文本,如何对单元格中的数字求和?