duan201444 2015-04-11 17:38
浏览 26
已采纳

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

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条回答 默认 最新

  • doujingya1166 2015-04-11 17:44
    关注

    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
    ", data.Strings)
    

    <kbd>Live Demo</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题