如何按 float64 值对 map[string]float64 进行排序?

我正在努力理解如何简单地对map[string]float64. 我看了一下如何按其值对 Map[string]int 进行排序?sort.Sort,这建议使用 struct 进行排序,但是当func 期望func(i, j int)而不是时,我不确定如何执行此操作func(i, j float64)。


例如,这将如何排序?


data := make(map[string]float64)

data["red"] = 1.00

data["green"] = 3.00

data["blue"] = 2.00

我尝试了以下方法,但仅按string地图中的排序,而不是实际排序float64:


data := make(map[string]float64)

data["red"] = 1.00

data["green"] = 3.00

data["blue"] = 2.00


var keys []string

var values []float64

for key, cost := range data {

    keys = append(keys, key)

    costs = append(costs, cost)

}

sort.Strings(keys)

sort.Float64s(values)

for _, key := range keys {

    fmt.Printf("%s %v\n", key, data[key])

}


蝴蝶不菲
浏览 166回答 2
2回答

慕村225694

它期望int而不是float64因为i, j是用于比较和交换切片中的元素的索引。我建议你应该使用一个新的结构并为它实现 sort.Interface:type MapData struct {&nbsp; &nbsp; Key&nbsp; &nbsp;string&nbsp; &nbsp; Value float64}type MapSort []*MapDatafunc (m MapSort) Len() int {&nbsp; &nbsp; return len(m)}func (m MapSort) Less(i, j int) bool {&nbsp; &nbsp; return m[i].Value < m[j].Value}func (m MapSort) Swap(i, j int) {&nbsp; &nbsp; m[i], m[j] = m[j], m[i]}

萧十郎

这是我用来成功排序的内容:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math"&nbsp; &nbsp; "sort")// round a float64 to 2 decimal places.func round(n float64) float64 {&nbsp; &nbsp; return math.Round(n*100) / 100}type Pair struct {&nbsp; &nbsp; Key&nbsp; &nbsp;string&nbsp; &nbsp; Value float64}type PairList []Pairfunc (p PairList) Len() int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ return len(p) }func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }func (p PairList) Swap(i, j int)&nbsp; &nbsp; &nbsp; { p[i], p[j] = p[j], p[i] }func main() {&nbsp; &nbsp; data := make(map[string]float64)&nbsp; &nbsp; data["red"] = 1.00&nbsp; &nbsp; data["green"] = 3.00&nbsp; &nbsp; data["blue"] = 2.00&nbsp; &nbsp; var i int&nbsp; &nbsp; sorted := make(PairList, len(data))&nbsp; &nbsp; for key, value := range data {&nbsp; &nbsp; &nbsp; &nbsp; sorted[i] = Pair{key, value}&nbsp; &nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; }&nbsp; &nbsp; sort.Sort(sort.Reverse(sorted))&nbsp; &nbsp; for _, pair := range sorted {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s %v\n", pair.Key, round(pair.Value))&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go