英文:
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)
英文:
Implement the sort.Interface
interface for a type that stores the data and the weights:
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]
}
Then call sort.Sort
on it:
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)
<kbd>Live Demo</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论