在 golang 中对结构图进行排序

我有一张像这样的地图


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

Key: 9970DLXEVOQ01 Value: [{9972IOFNIDER6 0.3}]

Key: 9970QYPOYUUIO Value: [{9972VOFA3OJLK 0.4}]

在名为product_deal 的golang中,键是字符串,值是结构:


type product_detail struct {

     deal_id string

     rating float64

}

我需要根据每个值字段中的评级(降序)对值进行排序,输出应该是


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

Key: 9970DLXEVOQ01 Value: [{9972IOFNIDER6 0.3}]

Key: 9970QYPOYUUIO Value: [{9972VOFA3OJLK 0.4}]

有关如何完成此操作的任何想法。我确实看过其他帖子,这些帖子对地图进行了排序,但无法获得实现。任何帮助,将不胜感激。


芜湖不芜
浏览 247回答 1
1回答

陪伴而非守候

为了扩展我对原始问题的评论,这里有一个可以在Go playground上运行的工作示例。请注意,我可能误解了您想要的类型的结构,但这个想法应该很清楚。package mainimport "fmt"import "sort"type Product struct {&nbsp; &nbsp; Id&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; Rating float64}type Deal struct {&nbsp; &nbsp; Id&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; products []Product}type Deals []Deal// Ensure it satisfies sort.Interfacefunc (d Deals) Len() int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ 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)&nbsp; &nbsp; &nbsp; { d[i], d[j] = d[j], d[i] }func main() {&nbsp; &nbsp; deals := Deals{&nbsp; &nbsp; &nbsp; &nbsp; {"9970DLXEVOQ0O", []Product{{"9972MFYWYJIEK", 0.2}}},&nbsp; &nbsp; &nbsp; &nbsp; {"9970DLXEVOQ01", []Product{{"9972IOFNIDER6", 0.3}}},&nbsp; &nbsp; &nbsp; &nbsp; {"9970QYPOYUUIO", []Product{{"9972VOFA3OJLK", 0.4}}},&nbsp; &nbsp; &nbsp; &nbsp; {"9970DLYKLAO8O", []Product{{"9972IOFNIDER6", 0.3}}},&nbsp; &nbsp; &nbsp; &nbsp; {"9970QYPMNAUUI", []Product{{"9972QIUUINW6R", 0.5}}},&nbsp; &nbsp; }&nbsp; &nbsp; sort.Sort(deals)&nbsp; &nbsp; for _, d := range deals {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(d)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go