【问题标题】:How to count number of occurrences of a value in a map with Golang?如何使用 Golang 计算地图中某个值的出现次数?
【发布时间】:2019-07-26 08:57:57
【问题描述】:

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

m := make(map[int]Record)

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", "Year": 1996}

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

【问题讨论】:

  • 地图map[int]Record中的关键是什么,或者说这不重要吗?第二张地图的钥匙是什么?是(年份、类型)吗?
  • map[int]Record 中的键只是一个计数器(Record 条目来自在代码的早期阶段解析的 xml),所以它并不重要。对于第二张地图,键应该是年份,输入(SumRecord 结构)。

标签: dictionary go sum


【解决方案1】:

这是@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",
}])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多