如何按照 map 的值对切片进行排序

huangapple go评论90阅读模式
英文:

How do I sort a slice by values of a map

问题

看起来是一个基本的问题,但找不到简单的答案。

我有一个切片:

[]string{"dog", "cat", "bird"}

通过查找映射中的排序值,最好的方法是如何对其进行排序:

map[string]int{"dog": 2, "cat":3, "bird": 1}

这样切片的顺序如下:

[]string{"bird", "dog", "cat"}
英文:

Seems a basic question, but can't find a simple answer.

I have a slice:

[]string{"dog", "cat", "bird"}

What's the best way to sort it by looking up the sorting values in a map:

map[string]int{"dog": 2, "cat":3, "bird": 1}

So that the slice is ordered as below:

[]string{"bird", "dog", "cat"}

答案1

得分: 5

实现一个类型,该类型存储数据和权重,并为其实现sort.Interface接口:

import "sort"

type WeightedStringSlice struct {
    Strings []string
    Weights map[string]int
}

func (s *WeightedStringSlice) Len() int {
    return len(s.Strings)
}

func (s *WeightedStringSlice) Less(i, j int) bool {
    return s.Weights[s.Strings[i]] < s.Weights[s.Strings[j]]
}

func (s *WeightedStringSlice) Swap(i, j int) {
    s.Strings[i], s.Strings[j] = s.Strings[j], s.Strings[i]
}

然后在该类型上调用sort.Sort

data := WeightedStringSlice{
    Strings: []string{"dog", "cat", "bird"},
    Weights: map[string]int{"dog": 2, "cat": 3, "bird": 1},
}
sort.Sort(&data)
fmt.Printf("%v\n", data.Strings)

Live Demo

英文:

Implement the sort.Interface interface for a type that stores the data and the weights:

import &quot;sort&quot;

type WeightedStringSlice struct {
	Strings []string
	Weights map[string]int
}

func (s *WeightedStringSlice) Len() int {
	return len(s.Strings)
}

func (s *WeightedStringSlice) Less(i, j int) bool {
	return s.Weights[s.Strings[i]] &lt; s.Weights[s.Strings[j]]
}

func (s *WeightedStringSlice) Swap(i, j int) {
	s.Strings[i], s.Strings[j] = s.Strings[j], s.Strings[i]
}

Then call sort.Sort on it:

data := WeightedStringSlice{
	Strings: []string{&quot;dog&quot;, &quot;cat&quot;, &quot;bird&quot;},
	Weights: map[string]int{&quot;dog&quot;: 2, &quot;cat&quot;: 3, &quot;bird&quot;: 1},
}
sort.Sort(&amp;data)
fmt.Printf(&quot;%v\n&quot;, data.Strings)

<kbd>Live Demo</kbd>

huangapple
  • 本文由 发表于 2015年4月12日 01:38:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/29580955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定