英文:
Nested Range Loop with Map Optimization
问题
我正在尝试从一个结构体字段中收集所有的X和Y值,并将属于同一X值的Y值放入一个映射中,但它嵌套了3层。
目前,我正在使用以下代码:
topClasses := make([]TopClass, 0)
// 在这里填充topClasses切片
KeyValueMap := make(map[int][]int)
for _, nestedClass := range topClasses {
for _, nestedItem := range nestedClass.nestedList {
for _, value := range nestedItem.Values {
if _, found := KeyValueMap[value.X]; !found {
KeyValueMap[value.X] = []int{value.Y}
} else {
KeyValueMap[value.X] = append(KeyValueMap[value.X], value.Y)
}
}
}
}
以下是结构体的实现方式:
type TopClass struct {
nestedList []ListClass
}
type ListClass struct {
Values []Value
}
type Value struct {
X int
Y float64
}
即使我正在使用映射,是否有更高效的方法可以使用goroutines、channels和/或waitgroups等来完成这个任务?
英文:
I am trying to collect all X and Y values from a Struct field and place Y values that belong to the same X value in a map, but it is nested 3 levels down.
Currently, I am using the following code:
topClasses := make([]TopClass, 0)
// populate topClasses Slice here
KeyValueMap := make(map[int][]int)
for _, nestedClass := range topClasses {
for _, nestedItem := range nestedClass.nestedList {
for _, value := range nestedItem.Values {
if _, found := KeyValueMap[value.X]; !found {
KeyValueMap[value.X] = []int{value.Y}
} else {
KeyValueMap[value.X] = append(KeyValueMap[value.X], value.Y)
}
}
}
}
Below is how the Structs are implemented:
type TopClass struct {
nestedList []ListClass
}
type ListClass struct {
Values []Value
}
type Value struct {
X int
Y float64
}
Is there a more efficient way to do this using goroutines, channels, and/or waitgroups, etc. even though I am working with maps?
答案1
得分: 1
以下代码在键已经存在的情况下消除了额外的映射查找。它也更短。
KeyValueMap := make(map[int][]int)
for _, nestedClass := range topClass {
for _, nestedItem := range nestedClass.nestedList {
for _, value := range nestedItem.Values {
KeyValueMap[value.X] = append(KeyValueMap[value.X], value.Y)
}
}
}
英文:
The following code eliminates an extra map lookup in the case where the key is already present. It's also shorter.
KeyValueMap := make(map[int][]int)
for _, nestedClass := range topClass {
for _, nestedItem := range nestedClass.nestedList {
for _, value := range nestedItem.Values {
KeyValueMap[value.X] = append(KeyValueMap[value.X], value.Y)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论