我正在嘗試按其字段之一對(duì)(Golang)結(jié)構(gòu)切片進(jìn)行排序。我看了很多示例、go-playgrounds 和文檔,我覺(jué)得我明白了,但我仍然無(wú)法讓我的代碼正常工作。package mainimport (? ? "fmt"? ? "sort")type Method struct {? ? MethodNumber int? ? ? ?`json:"methodNumber"`? ? MethodRank? ?int? ? ? ?`json:"rank"`? ? MethodRMSE? ?float64? ?`json:"error"`? ? Forecast? ? ?[]float64 `json:"forecast"`}// extra stuff for sorting.type ByError []Methodfunc (s ByError) Len() int {? ? return len(s)}func (s ByError) Swap(i, j int) {? ? s[i], s[j] = s[j], s[i]}func (s ByError) Less(i, j int) bool {? ? return s[i].MethodRMSE < s[i].MethodRMSE}func main() {? ? xs := make([]Method, 0)? ? fmt.Println(len(xs))? ? xs = append(xs, Method{MethodNumber: 1, MethodRMSE: 10})? ? xs = append(xs, Method{MethodNumber: 2, MethodRMSE: 8})? ? xs = append(xs, Method{MethodNumber: 3, MethodRMSE: 6})? ? xs = append(xs, Method{MethodNumber: 4, MethodRMSE: 4})? ? fmt.Printf("%+v \n", xs)? ? sort.Sort(ByError(xs))? ? fmt.Printf("%+v \n", xs)? ? sort.Sort(sort.Reverse(ByError(xs)))? ? fmt.Printf("%+v \n", xs)}我的非工作代碼:https://play.golang.org/p/h8SHVjTQSPM我的應(yīng)該按 RMSE 排序,但它根本不會(huì)改變順序?,F(xiàn)在,我的 go playground 的結(jié)果應(yīng)該是按 RMSE 升序排序,然后反向排序。
1 回答

海綿寶寶撒
TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
這里打字錯(cuò)誤
func (s ByError) Less(i, j int) bool { return s[i].MethodRMSE < s[i].MethodRMSE }
應(yīng)該
func (s ByError) Less(i, j int) bool { return s[i].MethodRMSE < s[j].MethodRMSE }
因?yàn)樗悬c(diǎn)難看,第一個(gè)(錯(cuò)誤的)版本將項(xiàng)目與自身進(jìn)行比較(兩個(gè)索引都是i
)。第二個(gè)正確地使用了i
和j
。
- 1 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報(bào)
0/150
提交
取消