我创建了一个具有以下结构的 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/