2017-09-13 46 views
0
type Item struct { 
    Y int 
    X int 
    otherProp int 
} 

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

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

+6

您比较X和Y值。你能举一个你难以做到这一点的例子吗? ('sort.Slice'不是必需的,你也可以用标准的'sort.Sort'来完成。) – JimB

+4

这个软件包甚至包含了一个例子:https:// golang。组织/包装/排序/#example__sortMultiKeys。或者,您可以分类两次:先在Y上,然后在X上稳定(!)。 – Volker

+0

您能给出预期行为的示例吗? – tgogos

回答

0

继从这里第一个例子: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 
] 
1

[...]有没有解决这个无过片多次循环,一个简单的方法?

否。基于比较的排序基本上总是涉及至少循环切片一次再加上多一点。但不要担心:排序。切片不会做太多的工作。

你的问题是?

相关问题