亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按數字和字母順序對基于結構的切片進行排序

按數字和字母順序對基于結構的切片進行排序

Go
收到一只叮咚 2022-05-23 17:34:16
我有一片這樣的結構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

})


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號