英文:
Converting an []slice to an []map with same keys for every slice
问题
你好,我正在尝试将一个 []slice 转换为具有相同键的 []map。
使用情况如下:假设你正在尝试将 Excel 表格解析为一个 map。你知道标题列是一个字符串切片。然后,你以 [][]string 的格式获取行数据。为了得到一个 map,你必须将标题值设置给每一行中的每个项目。
我目前的实现如下:
package main
import (
"fmt"
)
func main() {
header := []string{"first", "second", "third"}
rows := [][]string{{"1.1", "1.2", "1.3"}, {"2.1", "2.2", "2.3"}, {"3.1", "3.2", "3.3"}}
length := len(header)
var values []map[string]interface{}
for _, row := range rows {
dict := map[string]interface{}{}
for i, val := range row {
if i < length {
dict[header[i]] = val
}
}
values = append(values, dict)
}
fmt.Println(values)
}
Go Playground 链接:https://play.golang.org/p/Ags779GVtD7
问题在于复杂性,因为你必须遍历所有行,然后再通过循环设置每一行的键。
如果有更高效的方法,请提供建议,谢谢!
英文:
Hi I am trying to convert an []slice to a []map with the same keys for every map value.
The use case is the following: suppose you are trying to parse an excel sheet to a map. You know the header column as a slice of strings. You then get the rows in the format [][]string. To get a map you must set the header values to each item in each row.
My current implementation is the following
package main
import (
"fmt"
)
func main() {
header := []string{"first", "second", "third"}
rows := [][]string{{"1.1", "1.2", "1.3"}, {"2.1", "2.2", "2.3"}, {"3.1", "3.2", "3.3"}}
length := len(header)
var values []map[string]interface{}
for _, row := range rows {
dict := map[string]interface{}{}
for i, val := range row {
if i < length {
dict[header[i]] = val
}
}
values = append(values, dict)
}
fmt.Println(values)
}
Go playground link: https://play.golang.org/p/Ags779GVtD7
The issue here is complexity as you have to loop through all of the rows and then set the keys to each row by looping again.
Would be grateful for suggestions of a more efficient way of doing this.
答案1
得分: 3
这样做没有更高效的方法。如果你想将 n
个元素放入一个映射中,你必须执行 O(n)
次操作。而你的双重循环导致了 n
次插入调用。
英文:
There is no more efficient way to do this. If you want to put n
elements in a map you will have to do O(n)
operations. And your double loop results in n
insert call.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论