如何通过它的值对Map [string] int进行排序? [英] How to sort a Map[string]int by its values?

查看:194
本文介绍了如何通过它的值对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>

对于原文,请在此处找到 https://groups.google.com/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 https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw

这篇关于如何通过它的值对Map [string] int进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆