sorting - 如何按多个值对 go slice 进行排序?

标签 sorting go slice

type Item struct {
    Y    int
    X    int
    otherProp    int
}

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

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

最佳答案

按照此处的第一个示例: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
]

关于sorting - 如何按多个值对 go slice 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46199397/

相关文章:

c++ - 在C++中合并排序

python - 多维切片的紧凑符号

go - 在给定索引处的 slice 中插入一个值

rust - Rust 中是否有一个有效的函数可以找到排序向量中某个值第一次出现的索引?

python - 基于python中的两个变量排序

Perl 频率排序和其他东西

algorithm - 将STL映射转换为基于数值的键排序列表的好算法

git - 如何使用 go get checkout 版本?

go - 包导入,不能使用导入包中的结构

golang XML : unmarshal ignores namespace