按顺序收集值,每个值都包含一个映射 [英] Collect values in order, each containing a map

查看:19
本文介绍了按顺序收集值,每个值都包含一个映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中迭代返回的map时,由topic函数返回,key没有按顺序出现.

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 博客: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆