doudou521125 2016-07-26 04:56
浏览 52
已采纳

Golang:如何按星期几对切片进行排序?

I have a slice of strings which contains the days of the week like this:

days := []string{"M", "Th", "W", "F", "T", "S", "Su"}

How do I sort them so it will output like this:

[M T W Th F S Su]

starting with Monday.

  • 写回答

4条回答 默认 最新

  • dougekui1518 2016-07-26 05:08
    关注

    You can create a map keying days to their relative order. Then you can have a type implement sort.Interface interface:

    type Days []string
    
    // map to store weekdays' relative order
    var days = map[string]int{
        "M":  1,
        "T":  2,
        "W":  3,
        "Th": 4,
        "F":  5,
        "S":  6,
        "Su": 7,
    }
    
    func (d Days) Len() int      { return len(d) }
    func (d Days) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
    func (d Days) Less(i, j int) bool {
        return days[d[i]] < days[d[j]]
    }
    
    func main() {
        ds := Days([]string{"M", "Th", "W", "F", "T", "S", "Su"})
    
        sort.Sort(ds)
        fmt.Println(ds)
    }
    

    Example: https://play.golang.org/p/lzdfI-1BJK

    If you want you can move days in Less method to avoid globals. But that would be severely inefficient since the map will be initialized for each element of Days.

    Another implementation would be to have a pre-declared slice with the days in correct order and then use strings.Index in Less. This would perform slower but since your slice is of fixed length and very small (only 7 elements), it shouldn't be much of an issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab