如何按地图的值对切片进行排序

js8*_*837 3 sorting go

似乎是一个基本问题,但找不到简单的答案.

我有一个片段:

[]string{"dog", "cat", "bird"}
Run Code Online (Sandbox Code Playgroud)

通过在地图中查找排序值来对其进行排序的最佳方法是什么:

map[string]int{"dog": 2, "cat":3, "bird": 1}
Run Code Online (Sandbox Code Playgroud)

因此切片的排序如下:

[]string{"bird", "dog", "cat"}
Run Code Online (Sandbox Code Playgroud)

rig*_*old 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]
}
Run Code Online (Sandbox Code Playgroud)

然后打电话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)
Run Code Online (Sandbox Code Playgroud)

Live Demo