不为别的,只为做一个连自己都羡慕的人

go对数组对象排序

1.根据时间对数组对象排序

package main
import (
    "fmt"
    "time"
    "github.com/ahmetb/go-linq/v3"
)
type CustomTime time.Time

func (a CustomTime) CompareTo(c linq.Comparable) int {
    aa := time.Time(a)
    bb := time.Time(c.(CustomTime))
    if aa.After(bb) {
        return 1
    } else if aa.Equal(bb) {
        return 0
    } else {
        return -1
    }
}

type StudyTrainParams struct {
    Loss string
    Optimizer string
    Epochs string
    BatchSize string
    OperationHours string
    FileName string
    FullPath string
    Accuracy string
    UserId int
}
//对时间进行排序
var orderedList []StudyTrainParams
linq.From(res).OrderByDescending(func(i interface{}) interface{} { return common.CustomTime(i.(StudyTrainParams).CreatedAt) }).ToSlice(&orderedList)

2.根据float64类型的数据,对数组对象排序

type CpuList struct {
    Username string `json:"username"`
    Memory float64 `json:"memory"`
}
// RandomFloat64 Random 根据区间产生随机数 Float64
func RandomFloat64(min, max float64,send int) float64 {
    rand.Seed(int64(send+time.Now().Day()))
    return min + rand.Float64() * (max - min)
}
var cpuList []CpuList
for i := 0; i < 10; i++ {
    tempcpu:=CpuList{
        Username:value.Name,
        Memory:RandomFloat64(100,1000,55555),
    }
    cpuList= append(cpuList, tempcpu)
}

sort.Slice(cpuList, func(i, j int) bool { return cpuList[i].Memory > cpuList[j].Memory })

3. 对纯float类型的数组做排序

var cpuList []string{1.11,1.25,0.12,3.65,1.15}
sort.Sort(sort.Reverse(sort.Float64Slice(cpuList)))  //对float64数据进行从大到小排序

 

posted @ 2022-11-19 15:21  升级打怪  阅读(413)  评论(0编辑  收藏  举报