大家好,我是Golang社区主编彬哥,这篇是给大家讲解关于复杂数据结构排序的。
结构体,数据排序
package main
import (
"fmt"
"sort"
"strconv"
)
var testmap map[string]Person
type Person struct {
Name string
Age int
Sex string
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
//func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Less(i, j int) bool { return a[i].Age > a[j].Age } // 从大到小排序
func init() {
testmap = make(map[string]Person)
var testmap1 Person
testmap1.Name = "John"
testmap1.Age = 31
testmap1.Sex = "1"
testmap["3"] = testmap1
testmap1.Name = "Bob1"
testmap1.Age = 31
testmap1.Sex = "1"
testmap["0"] = testmap1
testmap1.Name = "Bob"
testmap1.Age = 31
testmap1.Sex = "1"
testmap["2"] = testmap1
testmap1.Name = "John1"
testmap1.Age = 31
testmap1.Sex = "1"
testmap["4"] = testmap1
testmap1.Name = "John2"
testmap1.Age = 31
testmap1.Sex = "1"
testmap["5"] = testmap1
testmap1.Name = "John3"
testmap1.Age = 31
testmap1.Sex = "1"
testmap["6"] = testmap1
}
func main() {
fmt.Println(len(testmap))
people := make([]Person, len(testmap))
// 1 结构提取值获取数据 append
for key, second := range testmap {
ikey, _ := strconv.Atoi(key)
fmt.Println(people) // 从0开始的
people = append(people, people[ikey])
people[ikey] = second
}
// 排序
sort.Sort(ByAge(people))
fmt.Println(people)
// 获取数据值
for key, second := range people {
fmt.Println(key) // 从0开始的
fmt.Println(second.Name)
// 组合排名
}
}
输出结果:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有