string - 映射字符串中的有序迭代

标签 string go

在 Go 博客中,这是按顺序打印 map 的方法。

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 这样的字符串键呢?

我不知道如何按顺序打印出字符串(未排序,按照在 map 容器中创建字符串的顺序)

这个例子在我的 Playground 上http://play.golang.org/p/Tt_CyATTA3 如您所见,它一直在打印困惑的字符串,所以我尝试将整数值映射到 map[string]string 但我仍然无法弄清楚如何映射 map[string 的每个元素]字符串

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

最佳答案

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

"...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"

这个解决方案有点简单,你有一个单独的 slice ,其中的键可以根据需要排序:

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

因此,要按预期工作,请创建一个具有正确顺序的额外 slice ,然后迭代结果并按该顺序打印。

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
}

看到它在这里运行:http://play.golang.org/p/GsDLXjJ0-E

关于string - 映射字符串中的有序迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19127121/

相关文章:

python - 如何在Python中编写一个分割字符串并将其转换为字典的函数

javascript - 从/r/listenToThis 解析歌曲标题以获取 IFTTT 小程序

从接口(interface)获取指向结构的指针?

node.js - 使用socket.io连接node js服务器和golang服务器有什么缺点?

go - Go 中具有作用域的多组 const 名称

python - 读取值并将它们写为逗号分隔值 python

c# - 只复制不同的到第二个数组

c++ - 转换浮点值时设置 std::to_string 的精度

reflection - 用反射填充 map 中的结构

regex - golang选择性地将字符串转换为小写