首页 > 编程语言 > 详细

golang之map排序

时间:2020-08-10 09:14:38      阅读:90      评论:0      收藏:0      [点我收藏+]

map按key顺序获取value

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := make(map[string]int, 5)
    fmt.Printf("%T[%p](%d): %v\n", m, &m, len(m), m)
    m["wang"] = 1
    m["wangq"] = 2
    m["wangh"] = 3
    m["hua"] = 4
    m["huaq"] = 5
    fmt.Printf("%T[%p](%d): %v\n", m, &m, len(m), m)
    m["huaw"] = 6
    m["qing"] = 7
    m["qingw"] = 8
    fmt.Printf("%T[%p](%d): %v\n", m, &m, len(m), m)

    mlen := len(m)
    ss := make([]string, 0, mlen)
    for k := range m {
        ss = append(ss, k)
    }
    sort.Strings(ss)
    sort.Sort(sort.Reverse(sort.StringSlice(ss)))
    fmt.Println(ss)
    for _, v := range ss {
        fmt.Printf("%s:%d ", v, m[v])
    }
}
//////
map[string]int[0xc000136018](0): map[]
map[string]int[0xc000136018](5): map[hua:4 huaq:5 wang:1 wangh:3 wangq:2]
map[string]int[0xc000136018](8): map[hua:4 huaq:5 huaw:6 qing:7 qingw:8 wang:1 wangh:3 wangq:2]
[wangq wangh wang qingw qing huaw huaq hua]
wangq:2 wangh:3 wang:1 qingw:8 qing:7 huaw:6 huaq:5 hua:4 

注:map() make时大小无关,An empty map is allocated with enough space to hold the specified number of elements. The size may be omitted, in which case a small starting size is allocated.

 

golang之map排序

原文:https://www.cnblogs.com/embedded-linux/p/13467013.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!