go对列表和字典排序

对列表的排序,使用sort.Slice即可,但是去重没有直接的方法,需要遍历

package main

import (
	"fmt"
	"sort"
)

func main() {
	//初始化列表和字典
	res := make([]int, 0)
	mp := make(map[int]bool, 0)
	var arr []int
	for x := 1; x < 10; x += 2 {
		res = append(res, x)
	}
	for x := -3; x < 12; x += 3 {
		res = append(res, x)
	}
	for x := 2; x < 10; x++ {
		res = append(res, x)
	}
	fmt.Println(res)
	//去重
	for _, e := range res {
		if mp[e] == false {
			mp[e] = true
			arr = append(arr, e)
		}
	}
	//排序
	sort.Slice(res, func(i, j int) bool {
		return res[i] > res[j]
	})

	fmt.Println(res)
	fmt.Println(arr)
}

输出为:

[1 3 5 7 9 -3 0 3 6 9 2 3 4 5 6 7 8 9]
[9 9 9 8 7 7 6 6 5 5 4 3 3 3 2 1 0 -3]
[1 3 5 7 9 -3 0 6 2 4 8]  

字典排序:

package main

import (
	"fmt"
	"sort"
)

func main() {
	//初始化列表和字典
	res := make([]int, 0)
	mp := make(map[int]int, 0)
	type kv struct {
		key   int
		value int
	}
	var ss []kv
	for x := 1; x < 10; x += 2 {
		res = append(res, x)
	}
	for x := -3; x < 12; x += 3 {
		res = append(res, x)
	}
	for x := 2; x < 10; x++ {
		res = append(res, x)
	}
	fmt.Println(res)
	for _, e := range res {
		if mp[e] == 0 {
			mp[e] = 1

		} else {
			mp[e] += 1
		}
	}

	for k, v := range mp {
		ss = append(ss, kv{k, v})
	}
	//按照键排序
	sort.Slice(ss, func(i, j int) bool {
		return ss[i].key > ss[j].key
	})
	fmt.Println(res)
	fmt.Println(ss)
}

输出为:

[1 3 5 7 9 -3 0 3 6 9 2 3 4 5 6 7 8 9]
[1 3 5 7 9 -3 0 3 6 9 2 3 4 5 6 7 8 9]
[{9 3} {8 1} {7 2} {6 2} {5 2} {4 1} {3 3} {2 1} {1 1} {0 1} {-3 1}]

你可能感兴趣的:(go,golang,算法)