2 回答
TA贡献1853条经验 获得超9个赞
package main
import (
"fmt"
"sort"
"strconv"
)
type Rooms struct {
Type string
Total string
}
func main() {
CombinedRooms := [][]Rooms{
{Rooms{Type: "c", Total: "2"}, Rooms{Type: "b", Total: "1"}, Rooms{Type: "f", Total: "10"}},
{Rooms{Type: "d", Total: "5"}, Rooms{Type: "a", Total: "0"}},
}
fmt.Println(CombinedRooms)
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
})
}
fmt.Println(CombinedRooms)
sort.Slice(CombinedRooms[:], func(i, j int) bool {
for x := range CombinedRooms[i] {
netRateJ, _ := strconv.Atoi(CombinedRooms[i][x].Total)
netRateK, _ := strconv.Atoi(CombinedRooms[j][x].Total)
if netRateJ == netRateK {
continue
}
return netRateJ < netRateK
}
return false
})
fmt.Println(CombinedRooms)
}
我现在明白你的问题了,上面的解决方案尝试通过比较每个内部切片元素来对外部切片中的内部切片进行排序(其中应该对内部切片元素进行排序)。如果你想要更好的,我相信你必须把切片压平并分类。
TA贡献1906条经验 获得超3个赞
您的示例https://play.golang.org/p/yyGygJyqtkn正确地对内部切片进行排序,它打印相同的输出,因为内部切片具有相同的值。但是,如果您还想根据内部切片的值对 CombinedRooms 进行排序,请添加以下代码:
sort.Slice(CombinedRooms, func(j, k int) bool {
netRateJ, _ := strconv.Atoi(CombinedRooms[j][0].Total)
netRateK, _ := strconv.Atoi(CombinedRooms[k][0].Total)
return netRateJ < netRateK
})
在这里找到工作代码https://play.golang.org/p/LLCeJdlE-hM
- 2 回答
- 0 关注
- 137 浏览
添加回答
举报