【问题标题】:How do I sort a go slice by multiple values?如何按多个值对 go 切片进行排序?
【发布时间】:2018-02-22 06:35:33
【问题描述】:
type Item struct {
    Y    int
    X    int
    otherProp    int
}

我有一些类似上面的结构。如何像 SQL 中的 ORDER BY X,Y 那样先按 X 值然后按 Y 值对切片 item []Item 进行排序?

我看到你可以使用 sort.Slice() 从 go 1.8 开始,但是有没有一种简单的方法可以解决这个问题而无需多次循环切片?

【问题讨论】:

  • 您比较 X 和 Y 值。你能举一个例子说明你在哪里做这件事吗? (sort.Slice 不是必需的,您也可以使用标准的 sort.Sort 来执行此操作。)
  • 该软件包甚至包含一个在一般情况下如何执行此操作的示例:golang.org/pkg/sort/#example__sortMultiKeys。或者,您可以排序两次:首先在 Y 上,然后在 X 上稳定 (!)。
  • 你能举一个预期行为的例子吗?

标签: sorting go slice


【解决方案1】:

[...] 有没有一种简单的方法可以解决这个问题而无需多次循环切片?

没有。基于比较的排序基本上总是涉及在切片上循环至少一次加多一点。不过不用担心:sort.Slice 不会做太多工作。

你有什么问题?

【讨论】:

    【解决方案2】:

    按照这里的第一个示例:Package sort,我写了以下...

    Less() 函数中,我检查X 是否相等,如果相等,则检查Y

    playground demo

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    type Item struct {
        X    int
        Y    int
        otherProp    int
    }
    
    func (i Item) String() string {
        return fmt.Sprintf("X: %d, Y: %d, otherProp: %d\n", i.X, i.Y, i.otherProp)
    }
    
    // ByX implements sort.Interface for []Item based on
    // the X field.
    type ByX []Item
    
    func (o ByX) Len() int           { return len(o) }
    func (o ByX) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
    func (o ByX) Less(i, j int) bool { 
        if o[i].X == o[j].X {
            return o[i].Y < o[j].Y
        } else {
            return o[i].X < o[j].X
        }
    }
    
    func main() {
        items := []Item{
            {1,2,3},
            {5,2,3},
            {3,2,3},
            {9,2,3},
            {1,1,3},
            {1,0,3},
        }
    
        fmt.Println(items)
        sort.Sort(ByX(items))
        fmt.Println(items)
    
    }
    

    输出:

    [X: 1, Y: 2, otherProp: 3
     X: 5, Y: 2, otherProp: 3
     X: 3, Y: 2, otherProp: 3
     X: 9, Y: 2, otherProp: 3
     X: 1, Y: 1, otherProp: 3
     X: 1, Y: 0, otherProp: 3
    ]
    [X: 1, Y: 0, otherProp: 3
     X: 1, Y: 1, otherProp: 3
     X: 1, Y: 2, otherProp: 3
     X: 3, Y: 2, otherProp: 3
     X: 5, Y: 2, otherProp: 3
     X: 9, Y: 2, otherProp: 3
    ]
    

    【讨论】:

      猜你喜欢
      • 2013-03-20
      • 2016-12-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2016-02-20
      • 2021-08-15
      • 2021-02-06
      • 2020-06-08
      相关资源
      最近更新 更多