我有一片這樣的結構type Interval struct{ number float64 coordinate string}var data []Interval假設數據如下[]Interval{ Interval{ number: 1, coordinate: "x", }, Interval{ number: 8, coordinate: "y", }, Interval{ number: 2, coordinate: "x", }, Interval{ number: 5, coordinate: "y", }, Interval{ number: 5, coordinate: "x", }, Interval{ number: 6, coordinate: "y", }, Interval{ number: 3, coordinate: "x", }, Interval{ number: 7, coordinate: "y", },}我的問題是如何按numberand對其進行排序coordinate?我嘗試過使用以下排序方法,但這并不符合我的預期// sort method that I usesort.Slice(data, func(i, j int) bool { return data[i].number < data[j].number})結果:[{1 x} {2 x} {3 x} {5 y} {5 x} {6 y} {7 y} {8 y}]期待:[{1 x} {2 x} {3 x} {5 x} {5 y} {6 y} {7 y} {8 y}]差異: {5 y} {5 x}應該是{5 x} {5 y}提示:我的預期結果與python的函數相似sort非常感謝任何幫助
1 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
您的比較器函數不會coordinate在情況屬性number相等的情況下比較屬性。因此,如果排序算法不穩定,{5, x} 和 {5, y} 的位置可能是不確定的。
這是比較器功能的更新版本:
sort.Slice(data, func(i, j int) bool {
if data[i].number != data[j].number {
return data[i].number < data[j].number
}
return data[i].coordinate < data[j].coordinate
})
- 1 回答
- 0 關注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消