本文介绍了如何通过它的值对Map [string] int进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出这个代码块 $ $ p $ $ $ c $ map map [string] int {hello:10,foo:20, bar:20}
我想打印出来
foo,20 bar,20 hello,10按照从高到低的顺序排列
谢谢!
解决方案通过Andrew Gerrand找到Golang-nuts的答案可以通过编写len / less / swap函数来实现排序接口 / p> func rankByWordCount(wordFrequencies map [string] int)PairList { pl:= make(PairList,len(wordFrequencies) )i:= 0 for k,v:=范围wordFrequencies { pl [i] = Pair {k,v} i ++ } sort.Sort(sort.Reverse(pl))返回pl } 类型对结构{键字符串值int } 类型PairList [] Pair func(p PairList)Len()int {return len(p)} func(p PairLis t)Less(i,j int)bool {return p [i] .Value< (p,j)= p [j],p [i]} code>
对于原文,请在此处找到 groups.google/forum/#!topic/golang-nuts/FT7cjmcL7gw
Given this code block
map[string]int {"hello":10, "foo":20, "bar":20}I would like to print out
foo, 20 bar, 20 hello, 10In the order of highest to lowest
Thanks!
解决方案Found the answer on Golang-nuts by Andrew Gerrand
You can implement the sort interface by writing the len/less/swap functions
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] }For the original post, please find it here groups.google/forum/#!topic/golang-nuts/FT7cjmcL7gw
更多推荐
如何通过它的值对Map [string] int进行排序?
发布评论