在map中有序迭代字符串键值对。

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

Ordered iteration in map string string

问题

在Go博客中,这是如何按顺序打印地图的方法。

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

import "sort"

var m map[int]string
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}

但是如果我有像var m map[string]string这样的字符串键呢?

我无法弄清楚如何按顺序打印出字符串(不排序,按照地图容器中字符串的创建顺序)。

示例在我的游乐场上:http://play.golang.org/p/Tt_CyATTA3
正如你所看到的,它一直打印出混乱的字符串,所以我尝试将整数值映射到map[string]string,但我仍然无法弄清楚如何映射map[string]string的每个元素。

http://play.golang.org/p/WsluZ3o4qd

英文:

In the Go blog, this is how to print the map in order.

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

      import "sort"

      var m map[int]string
      var keys []int
      for k := range m {
          keys = append(keys, k)
      }
      sort.Ints(keys)
      for _, k := range keys {
          fmt.Println("Key:", k, "Value:", m[k])
      }

but what if I have the string keys like var m map[string]string

I can't figure out how to print out the string in order(not sorted, in order of string creation in map container)

The example is at my playground http://play.golang.org/p/Tt_CyATTA3
as you can see, it keeps printing the jumbled strings, so I tried map integer values to map[string]string but I still could not figure out how to map each elements of map[string]string.

http://play.golang.org/p/WsluZ3o4qd

答案1

得分: 4

好的,以下是翻译好的内容:

嗯,博客提到迭代顺序是随机的:

"...当使用范围循环迭代映射时,迭代顺序未指定,并且不能保证从一次迭代到下一次迭代的顺序相同。"

解决方案有点简单,你可以使用一个单独的切片来按你需要的顺序排序键:

"...如果你需要稳定的迭代顺序,你必须维护一个单独的数据结构来指定该顺序。"

所以,为了按你的期望工作,创建一个额外的切片以正确的顺序,并按照该顺序迭代结果并打印。

order := []string{"i", "we", "he", ....}

func String(result map[string]string) string { 
   for _, v := range order { 
      如果在结果中存在则打印它, 
   }
   ... 在最后打印所有未定义的内容 
  返回字符串值
}

在这里运行代码:http://play.golang.org/p/GsDLXjJ0-E

英文:

Well, the blog mentions that iteration order is randomized:

>"...When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next"

The solution is kind of trivial, you have a separate slice with the keys ordered as you need:

>"...If you require a stable iteration order you must maintain a separate data structure that specifies that order."

So, to work as you expect, create an extra slice with the correct order and the iterate the result and print in that order.

order := []string{"i", "we", "he", ....}

func String(result map[string]string) string { 
   for _, v := range order { 
      if present in result print it, 
   }
   ... print all the Non-Defined at the end 
  return stringValue
}

See it running here: http://play.golang.org/p/GsDLXjJ0-E

huangapple
  • 本文由 发表于 2013年10月2日 06:31:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/19127121.html
匿名

发表评论

匿名网友

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

确定