按顺序收集值,每个值都包含一个地图 [英] Collect values in order, each containing a map
问题描述
在主题函数返回的代码中遍历返回的映射时,键没有按顺序出现.
When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order.
如何使键按顺序排列/对地图进行排序,以便键按顺序排列且值对应?
How can I get the keys to be in order / sort the map so that the keys are in order and the values correspond?
这是代码.
推荐答案
Go blog: Go maps in action 有一个很好的解释.
使用范围循环迭代地图时,迭代顺序为未指定且不能保证在一次迭代中相同到下一个.由于 Go 1 运行时随机化地图迭代顺序,如程序员依赖于之前的稳定迭代顺序执行.如果您需要稳定的迭代顺序,则必须维护一个单独的数据结构来指定该顺序.
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. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order.
这是我修改后的示例代码版本:http://play.golang.org/p/dvqcGPYy3-
Here's my modified version of example code: http://play.golang.org/p/dvqcGPYy3-
package main
import (
"fmt"
"sort"
)
func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
// To store the keys in slice in sorted order
keys := make([]int, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Ints(keys)
// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}
输出:
Key: 0 Value: b
Key: 1 Value: a
Key: 2 Value: c
这篇关于按顺序收集值,每个值都包含一个地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!