如何按其值对 Map[string]int 进行排序?

时间:2023-03-31

浏览:493

作者:佚名

你在学习Golang相关的知识吗?本文《如何按其值对 Map[string]int 进行排序?》,主要介绍的内容就涉及到golang,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

鉴于此代码块

map[string]int {"hello":10, "foo":20, "bar":20}

我想打印出来

foo, 20
bar, 20
hello, 10

按照从高到低的顺序

正确答案

在 Andrew Gerrand 的 Golang-nuts 上找到了答案

您可以通过编写 len/less/swap 函数来实现排序接口

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](https://groups.google.com/forum/#!topic/golang- nuts/FT7cjmcL7gw)

以上就是《如何按其值对 Map[string]int 进行排序?》的详细内容,更多关于golang的资料请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页