将一个 []slice 转换为一个 []map,每个 slice 都具有相同的键。

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

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 (
    &quot;fmt&quot;
)

func main() {
    header := []string{&quot;first&quot;, &quot;second&quot;, &quot;third&quot;}
    rows := [][]string{{&quot;1.1&quot;, &quot;1.2&quot;, &quot;1.3&quot;}, {&quot;2.1&quot;, &quot;2.2&quot;, &quot;2.3&quot;}, {&quot;3.1&quot;, &quot;3.2&quot;, &quot;3.3&quot;}}

    length := len(header)

    var values []map[string]interface{}
    for _, row := range rows {
	    dict := map[string]interface{}{}
	    for i, val := range row {
		    if i &lt; 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.

huangapple
  • 本文由 发表于 2021年9月24日 20:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/69314850.html
匿名

发表评论

匿名网友

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

确定