GolangNote

Golang笔记

Golang 按字符串长度对 slice 排序

Permalink

Go 语言内置的 sort 库可以对各种列表排序,这里是按 string slice 里的字符串长度排序。

Golang 按字符串长度对 slice 排序

Go: sort.Slice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fmt"
	"sort"
)

func main() {
	animals := []string{"snail", "dog", "cow", "elephant", "chicken", "mouse"}
	fmt.Println(animals)

	sort.Strings(animals) // 按 byte 排序
	fmt.Println(animals)

	sort.Slice(animals, func(i, j int) bool {
		return len(animals[i]) < len(animals[j]) // 按字符串长度 升序 排列
	})
	fmt.Println(animals)

	sort.Slice(animals, func(i, j int) bool {
		return len(animals[i]) > len(animals[j]) // 按字符串长度 降序 排列
	})
	fmt.Println(animals)
}

输出

: 结果
1
2
3
4
[snail dog cow elephant chicken mouse]
[chicken cow dog elephant mouse snail]
[cow dog mouse snail chicken elephant]
[elephant chicken mouse snail cow dog]

本文网址: https://golangnote.com/topic/299.html 转摘请注明来源

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Write a Comment to "Golang 按字符串长度对 slice 排序"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms