package main
import (
"fmt"
"sort"
)
func main() {
test := map[string]int{"wang":1,"liang":4,"lin":2,"dd":2,"haha":10}
haha := rankByWordCount(test)
fmt.Println(haha)
}
func rankByWordCount(wordFrequencies map[string]int) PairList{
pl := make(PairList, len(wordFrequencies))
i := 0
for k, v := range wordFrequencies {
pl[i] = Pair{k, v}
i++
}
//从小到大排序
//sort.Sort(pl)
//从大到小排序
sort.Sort(sort.Reverse(pl))
return pl
}
type Pair struct {
Key string
Value int
}
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func (p PairList) Swap(i, j int){ p[i], p[j] = p[j], p[i] }
go使用sort包对map进行排序
最新推荐文章于 2024-05-11 06:24:19 发布