AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

Go 語言中排序的三種方法

來源: 責編: 時間:2023-08-20 23:17:15 3325觀看
導讀在寫代碼過程中,排序是經常會遇到的需求,本文會介紹三種常用的方法。廢話不多說,下面正文開始。使用標準庫根據場景直接使用標準庫中的方法,比如:sort.Intssort.Float64ssort.Strings舉個例子:s := []int{4, 2, 3, 1}sort.I

dIr28資訊網——每日最新資訊28at.com

在寫代碼過程中,排序是經常會遇到的需求,本文會介紹三種常用的方法。dIr28資訊網——每日最新資訊28at.com

廢話不多說,下面正文開始。dIr28資訊網——每日最新資訊28at.com

使用標準庫

根據場景直接使用標準庫中的方法,比如:dIr28資訊網——每日最新資訊28at.com

  • sort.Ints
  • sort.Float64s
  • sort.Strings

舉個例子:dIr28資訊網——每日最新資訊28at.com

s := []int{4, 2, 3, 1}sort.Ints(s)fmt.Println(s) // [1 2 3 4]

自定義比較器

使用 sort.Slice 方法排序時,可以自定義比較函數 less(i, j int) bool,這樣就可以根據需要按不同的字段進行排序。dIr28資訊網——每日最新資訊28at.com

如果想要穩定排序的話,就使用 sort.SliceStable 方法。dIr28資訊網——每日最新資訊28at.com

舉個例子:dIr28資訊網——每日最新資訊28at.com

family := []struct {    Name string    Age  int}{    {"Alice", 23},    {"David", 2},    {"Eve", 2},    {"Bob", 25},}// Sort by age, keeping original order or equal elements.sort.SliceStable(family, func(i, j int) bool {    return family[i].Age < family[j].Age})fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

自定義數據結構

使用 sort.Sort 或者 sort.Stable 方法,它們可以對任意實現了 sort.Interface 的數據結構排序。dIr28資訊網——每日最新資訊28at.com

type Interface interface {    // Len is the number of elements in the collection.    Len() int    // Less reports whether the element with    // index i should sort before the element with index j.    Less(i, j int) bool    // Swap swaps the elements with indexes i and j.    Swap(i, j int)}

意思就是說,只要某一個數據結構實現了 Len() int,Less(i, j int) bool 和 Swap(i, j int) 這三個方法,那么就可以使用 sort.Sort 來排序。dIr28資訊網——每日最新資訊28at.com

舉個例子:dIr28資訊網——每日最新資訊28at.com

type Person struct {    Name string    Age  int}// ByAge implements sort.Interface based on the Age field.type ByAge []Personfunc (a ByAge) Len() int           { return len(a) }func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }func main() {    family := []Person{        {"Alice", 23},        {"Eve", 2},        {"Bob", 25},    }    sort.Sort(ByAge(family))    fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]}

字典排序

我們都知道,字典是無序的,具體原因可以看之前寫的這篇文章 Go 語言 map 如何順序讀???dIr28資訊網——每日最新資訊28at.com

如果想要字典按 key 或者 value 排序的話,可以這樣做。dIr28資訊網——每日最新資訊28at.com

m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}keys := make([]string, 0, len(m))for k := range m {    keys = append(keys, k)}sort.Strings(keys)for _, k := range keys {    fmt.Println(k, m[k])}// Output:// Alice 2// Bob 3// Cecil 1

以上就是本文的全部內容。dIr28資訊網——每日最新資訊28at.com

參考文章:

  • https://yourbasic.org/golang/how-to-sort-in-go/#performance-and-implementation

本文鏈接:http://www.tebozhan.com/showinfo-26-6191-0.htmlGo 語言中排序的三種方法

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: SpringBoot中的敏感信息的配置進行加密處理,這種方式你知道嗎?

下一篇: H5-Dooring可視化頁面制作神器測評總結

標簽:
  • 熱門焦點
Top