如何通过它的值对Map [string] int进行排序?

编程入门 行业动态 更新时间:2024-10-27 12:29:44
本文介绍了如何通过它的值对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, 10

In 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进行排序?

本文发布于:2023-07-15 18:10:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1112864.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Map   string   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!