gpt4 book ai didi

dictionary - 映射重复键值对(如果不存在)

转载 作者:行者123 更新时间:2023-12-01 21:17:08 28 4
gpt4 key购买 nike

以下是我的结构定义:

type test struct{
Title string
State string
Counts int
}

我想通过以下方式映射结构对象成员 map[Title:map[State:Counts]]
这是成功执行此操作的代码
func main() {
r := make(map[string]map[string]int)
r1 := make(map[string]int)
var ts []test

ts = append(ts, test{Title: "Push 1",
State: "Active",
Counts: 20})
ts = append(ts, test{Title: "Push 1",
State: "InActive",
Counts: 20})
ts = append(ts, test{Title: "Push 1",
State: "Checked",
Counts: 20})
ts = append(ts, test{Title: "Push 1",
State: "Active",
Counts: 23})

ts = append(ts, test{Title: "Push 2",
State: "Active",
Counts: 20})
ts = append(ts, test{Title: "Push 2",
State: "InActive",
Counts: 23})

for _, t := range ts {
r1[t.State] = t.Counts
r[t.Title] = r1

}
fmt.Println("struct: ", ts)
fmt.Println("map: ", r)
}

我面临的问题是没有 State: Checked的标题“Push 2”已附加上一个对象的Count值。
以下输出如下
struct: [{Push 1 Active 20} {Push 1 InActive 20} {Push 1 Checked 20} {Push 1 Active 23} {Push 2 Active 20} {Push 2 InActive 23}]
map: map[Push 1:map[Active:20 Checked:20 InActive:23] Push 2:map[Active:20 Checked:20 InActive:23]]

我编译的代码在去操场上。

最佳答案

r := make(map[string]map[string]int)仅创建一个 map ,没有任何条目。
r1 := make(map[string]int)也仅创建一个用于计数状态的 map ,但是您不需要一个 map ,每个不同的标题都需要一个单独的 map 。

因此,无需创建单个r1,而是根据需要创建内部 map 。遍历您的结构,并且当其标题没有内部映射时,请创建一个并将其存储在外部r映射中。

像这样:

for _, t := range ts {
counts := r[t.Title]
if counts == nil {
counts = make(map[string]int)
r[t.Title] = counts
}
counts[t.State]++

}

注意,计数操作可能只是 counts[t.State]++

有了这个输出将是(在 Go Playground上尝试):
map:  map[Push 1:map[Active:2 Checked:1 InActive:1] Push 2:map[Active:1 InActive:1]]

关于dictionary - 映射重复键值对(如果不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60184066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com