douzhannao5357 2013-09-09 09:34
浏览 170
已采纳

如何通过Map [string] int的值对其排序?

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!

  • 写回答

4条回答 默认 最新

  • dongtang5229 2013-09-09 09:57
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答