我正在嘗試按其字段之一對(Golang)結構切片進行排序。我看了很多示例、go-playgrounds 和文檔,我覺得我明白了,但我仍然無法讓我的代碼正常工作。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我的應該按 RMSE 排序,但它根本不會改變順序。現在,我的 go playground 的結果應該是按 RMSE 升序排序,然后反向排序。
1 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
這里打字錯誤
func (s ByError) Less(i, j int) bool { return s[i].MethodRMSE < s[i].MethodRMSE }
應該
func (s ByError) Less(i, j int) bool { return s[i].MethodRMSE < s[j].MethodRMSE }
因為它有點難看,第一個(錯誤的)版本將項目與自身進行比較(兩個索引都是i
)。第二個正確地使用了i
和j
。
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消