亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Golang 計算地圖中某個值的出現次數?

如何使用 Golang 計算地圖中某個值的出現次數?

Go
桃花長相依 2023-06-19 11:13:54
我創建了一個具有以下結構的地圖: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 實現它?
查看完整描述

1 回答

?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

這將創建 SumRecord 到整數的新映射,表示該特定類型/年份分組的出現次數總和。

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",

}])


查看完整回答
反對 回復 2023-06-19
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號