Golang map字典按照键排序和按照值排序
字典按键排序
package main
import (
"fmt"
"sort"
)
func main() {
m := map[string]int32{
"roy": 18,
"kitty": 16,
"hugo": 21,
"tina": 35,
"jason": 23,
}
lst := []string{}
for k, _ := range m {
lst = append(lst, k)
}
sort.Strings(lst) //排序字符串
fmt.Println(lst)
m1 := map[int]string{
19: "roy",
41: "kitty",
32: "jason",
23: "hugo",
}
lst1 := []int{}
for k, _ := range m1 {
lst1 = append(lst1, k)
}
sort.Ints(lst1) //排序int类型
fmt.Println(lst1)
}
通过结构体实现字典按值排序。
package main
import (
"fmt"
"sort"
)
func main() {
mapInfo := map[string]int32{
"roy":18,
"kitty":16,
"hugo":21,
"tina":35,
"jason":23,
}
type peroson struct {
Name string
Age int32
}
var lstPerson []peroson
for k, v := range mapInfo {
lstPerson = append(lstPerson, peroson {k, v})
}
sort.Slice(lstPerson, func(i, j int) bool {
return lstPerson[i].Age > lstPerson[j].Age // 降序
// return lstPerson[i].Age < lstPerson[j].Age // 升序
})
fmt.Println(lstPerson)
}
按值排序 转载自:https://www.golangnote.com/topic/75.html
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询