doulun0651 2014-03-13 01:11
浏览 63
已采纳

在golang中排序结构图

I have a map which is like this

Key: 9970DLXEVOQ0O Value: [{9972IOFNIDER6 0.3},{9972MFYWYJIEK 0.2},{9972QIUUINW6R 0.5}]
Key: 9970DLXEVOQ01 Value: [{9972IOFNIDER6 0.3}]
Key: 9970QYPOYUUIO Value: [{9972VOFA3OJLK 0.4}]

in golang named product_deal in which key is string and value is a struct :

type product_detail struct {
     deal_id string
     rating float64
}

I need to sort the values based on ratings(descending ) in each value field the output should be i.e

Key: 9970DLXEVOQ0O Value: [{9972QIUUINW6R 0.5},{9972IOFNIDER6 0.3},{9972MFYWYJIEK 0.2}]
Key: 9970DLXEVOQ01 Value: [{9972IOFNIDER6 0.3}]
Key: 9970QYPOYUUIO Value: [{9972VOFA3OJLK 0.4}]

Any ideas of how this needs to be done. i did have a look at other post which sort maps but could not get the implementation. Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • douwaz34842 2014-03-13 02:02
    关注

    To expand on my comment on the original question, here is a working example which can be run on the Go playground. Note that I may have misinterpreted the structure of the types you want to have, but the idea should be clear.

    package main
    
    import "fmt"
    import "sort"
    
    type Product struct {
        Id     string
        Rating float64
    }
    
    type Deal struct {
        Id       string
        products []Product
    }
    
    type Deals []Deal
    
    // Ensure it satisfies sort.Interface
    func (d Deals) Len() int           { return len(d) }
    func (d Deals) Less(i, j int) bool { return d[i].Id < d[j].Id }
    func (d Deals) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }
    
    func main() {
        deals := Deals{
            {"9970DLXEVOQ0O", []Product{{"9972MFYWYJIEK", 0.2}}},
            {"9970DLXEVOQ01", []Product{{"9972IOFNIDER6", 0.3}}},
            {"9970QYPOYUUIO", []Product{{"9972VOFA3OJLK", 0.4}}},
            {"9970DLYKLAO8O", []Product{{"9972IOFNIDER6", 0.3}}},
            {"9970QYPMNAUUI", []Product{{"9972QIUUINW6R", 0.5}}},
        }
    
        sort.Sort(deals)
    
        for _, d := range deals {
            fmt.Println(d)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站