对多维切片进行排序

想要根据 int 值对嵌套切片(升序到降序)进行排序,但切片不受影响。


以下是我正在尝试的简短片段。


type Rooms struct {

    type   string

    total  string

}


CombinedRooms := make([][]Rooms)


// sort by price

for i, _ := range CombinedRooms {

    sort.Slice(CombinedRooms[i], func(j, k int) bool {

        netRateJ, _ := strconv.Atoi(CombinedRooms[i][j].Total)

        netRateK, _ := strconv.Atoi(CombinedRooms[i][k].Total)

        return netRateJ < netRateK

    })

}

即使在排序功能之后,切片组合房间仍然不受影响。


添加一个小例子: https: //play.golang.org/p/yyGygJyqtkn


慕虎7371278
浏览 97回答 2
2回答

暮色呼如

package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sort"&nbsp; &nbsp; "strconv")type Rooms struct {&nbsp; &nbsp; Type&nbsp; string&nbsp; &nbsp; Total string}func main() {&nbsp; &nbsp; CombinedRooms := [][]Rooms{&nbsp; &nbsp; &nbsp; &nbsp; {Rooms{Type: "c", Total: "2"}, Rooms{Type: "b", Total: "1"}, Rooms{Type: "f", Total: "10"}},&nbsp; &nbsp; &nbsp; &nbsp; {Rooms{Type: "d", Total: "5"}, Rooms{Type: "a", Total: "0"}},&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(CombinedRooms)&nbsp; &nbsp; for i, _ := range CombinedRooms {&nbsp; &nbsp; &nbsp; &nbsp; sort.Slice(CombinedRooms[i], func(j, k int) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; netRateJ, _ := strconv.Atoi(CombinedRooms[i][j].Total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; netRateK, _ := strconv.Atoi(CombinedRooms[i][k].Total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return netRateJ < netRateK&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(CombinedRooms)&nbsp; &nbsp; sort.Slice(CombinedRooms[:], func(i, j int) bool {&nbsp; &nbsp; &nbsp; &nbsp; for x := range CombinedRooms[i] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; netRateJ, _ := strconv.Atoi(CombinedRooms[i][x].Total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; netRateK, _ := strconv.Atoi(CombinedRooms[j][x].Total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if netRateJ == netRateK {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return netRateJ < netRateK&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; })&nbsp; &nbsp; fmt.Println(CombinedRooms)}我现在明白你的问题了,上面的解决方案尝试通过比较每个内部切片元素来对外部切片中的内部切片进行排序(其中应该对内部切片元素进行排序)。如果你想要更好的,我相信你必须把切片压平并分类。

一只名叫tom的猫

您的示例https://play.golang.org/p/yyGygJyqtkn正确地对内部切片进行排序,它打印相同的输出,因为内部切片具有相同的值。但是,如果您还想根据内部切片的值对 CombinedRooms 进行排序,请添加以下代码:sort.Slice(CombinedRooms, func(j, k int) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; netRateJ, _ := strconv.Atoi(CombinedRooms[j][0].Total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; netRateK, _ := strconv.Atoi(CombinedRooms[k][0].Total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return netRateJ < netRateK&nbsp; &nbsp; })在这里找到工作代码https://play.golang.org/p/LLCeJdlE-hM
打开App,查看更多内容
随时随地看视频慕课网APP