在Go语言中,将映射项转换为平面数组可以使用以下方法:

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

Creating a flat array from the map entries in Go

问题

从一个映射中创建一个数组,同时保持时间复杂度较低的最短(且习惯用法)的方法是什么?

例如,从以下映射中:

map[string]string { "1":"a", "2":"b" }

我需要创建以下数组:

[]string{"1","a", "2","b"}

我可以在Scala中使用以下代码实现:

val myMap = Map("1" -> "a", "2" -> "b")
myMap.keySet ++ myMap.values

谢谢。

英文:

What is the shortest (and idiomatic) way to create an array from the keys and values of a map w/o compromising on time complexity too much?

For instance, from the following map:

map[string]string { "1":"a", "2":"b" }

I need to create the following array:

[]string{"1","a", "2","b"}

I can do this in Scala with following:

val myMap = Map("1" -> "a", "2" -> "b")
myMap.keySet ++ myMap.values

Thank you.

答案1

得分: 22

最简单的方法是遍历地图,因为在Go中,语法允许直接访问键和值,并将它们转储到数组中。

m := map[string]string{"1": "a", "2": "b"}
arr := []string{}
for k, v := range m {
   arr = append(arr, k, v)
}

这里有一个注意事项:在Go中,地图的迭代顺序是随机的,你可以在这里看到,参考"迭代顺序":

https://blog.golang.org/go-maps-in-action

因此,如果你希望最终的数组具有特定的顺序,你应该首先转储键和顺序(如同博客中所示)。

Playground(不包含排序部分):

https://play.golang.org/p/mCe6eEy25A

英文:

Simplest way would be to just iterate the map, since in Go the syntax would allow direct access to keys and values and dump them into the array.

m := map[string]string { "1":"a", "2":"b" }
arr := []string{}
for k, v := range m { 
   arr = append(arr, k, v)
}

One caveat here: In Go, map iteration order is randomized, as you can see here, under "Iteration Order":

https://blog.golang.org/go-maps-in-action

So if you want your resulting array to have a particular ordering, you should first dump the keys and order (as shown in that same blog entry).

Playground (without the sorting part):

https://play.golang.org/p/mCe6eEy25A

huangapple
  • 本文由 发表于 2017年8月8日 22:22:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/45570947.html
匿名

发表评论

匿名网友

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

确定