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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料