加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

按键排序golang映射值

发布时间:2020-12-16 18:03:49 所属栏目:大数据 来源:网络整理
导读:当迭代通过主题函数返回的代码中的返回映射时,键不会按顺序显示。 我如何获得按顺序排序/排序的地图,使键的顺序和值对应? 这里是the code。 Go blog: Go maps in action有一个很好的解释。 When iterating over a map with a range loop,the iteration or
当迭代通过主题函数返回的代码中的返回映射时,键不会按顺序显示。

我如何获得按顺序排序/排序的地图,使键的顺序和值对应?

这里是the code。

Go blog: Go maps in action有一个很好的解释。

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-

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
    var keys []int
    for k := range m {
        keys = append(keys,k)
    }
    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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读