如何按值对 Map[string]int 进行排序?
技术问答
299 人阅读
|
0 人回复
|
2023-09-12
|
鉴于此代码块+ P3 m$ F! `& ?( f4 }2 B
map[string]int {"hello":10,"foo":20,"bar":20}
2 b/ ]5 z9 b; f6 I 我想打印出来
. i3 }: J+ }9 i4 Cfoo,20bar,20hello,10
0 W4 ^% a9 U+ {6 U R' N+ i 按从高到低的顺序 P5 W3 o5 [8 |# b0 e4 j9 b
& T! S3 x1 V9 ]. V
解决方案:
1 @# s; O( }! e2 V/ x5 P+ E 你可以写 len/less/swap 函数实现排序接口5 @- L' `% D' k
func rankByWordCount(wordFrequencies map[string]int) PairList{ pl := make(PairList,len(wordFrequencies)) i := 0 for k,v := range wordFrequencies pl = Pair{k,v} i } sort.Sort(sort.Reverse(pl)) return pl}type Pair struct { Key string Value int}type PairList []Pairfunc (p PairList) Len() int { return len(p) }func (p PairList) Less(i,j int) bool { return p.Value < p[j].Value }func (p PairList) Swap(i,j int){ p,p[j] = p[j],p }6 n7 C/ j# Y6 ]& |5 p1 X. S- V
|
|
|
|
|
|