dictionary - 如果不存在,则映射重复键值对
问题描述
以下是我的结构定义:
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)
}
我面临的问题是标题“Push 2”没有State: Checked
附加上一个对象的计数值。以下输出如下
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]]
我编译的代码在 go playground。
解决方案
r := make(map[string]map[string]int)
只创建一个地图,它没有条目。
r1 := make(map[string]int)
也只创建一个地图来计算状态,但您不需要一个,您需要为每个不同的标题创建一个单独的地图。
因此,与其创建那个单一的r1
,不如按需创建内部地图。覆盖你的结构,当它的标题没有内部映射时,创建一个并将其存储在外部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]]
推荐阅读
- hyperledger - Hyperledger Composer 返回错误没有 GetState 的分类帐上下文
- mysql - 没有 -u root 的 mysql 命令在 rails 中不起作用
- c# - 将资源文件翻译成不同的语言
- mysql - MySQL - 获取字符串中分隔符之间的值
- java - 如何在 ArrayList 中搜索?
- matlab - 非线性数据的曲线拟合
- android-studio - Android Studio 3.2 菜单和文本变得不可读
- r - 删除空格并将字符转换为整个数据帧的较低值
- android - 来自 Firebase storageReference 的 getBytes 不起作用
- pandas - 熊猫 groupby 和排名 - 重复的排名相同