嵌套范围循环与映射优化

huangapple go评论102阅读模式
英文:

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)
        }
    }
}

huangapple
  • 本文由 发表于 2017年7月13日 17:08:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/45076178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定