给定此代码挡路
map[string]int {"hello":10, "foo":20, "bar":20}
我想打印出来
foo, 20
bar, 20
hello, 10
按从高到低的顺序
给定此代码挡路
map[string]int {"hello":10, "foo":20, "bar":20}
我想打印出来
foo, 20
bar, 20
hello, 10
按从高到低的顺序
在安德鲁·杰兰德的"高朗坚果"上找到了答案
您可以通过编写len/less/exchange函数来实现排序接口
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(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] }
对于原始帖子,请在此处找到https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw