[英]How to sort a map[string]float64 by the float64 value?
I'm struggling to understand how to simply sort a map[string]float64
.我正在努力理解如何简单地对
map[string]float64
排序。 I had a look at How to sort a Map[string]int by its values?我查看了如何按值对 Map[string]int 进行排序? , which suggests using a struct to do the sort, but I'm not sure how to do this when the
sort.Sort
func expects func(i, j int)
and not func(i, j float64)
. ,这建议使用结构进行排序,但是当
sort.Sort
func 需要func(i, j int)
而不是func(i, j float64)
时,我不确定如何执行此操作。
For example, how would this be sorted?例如,这将如何排序?
data := make(map[string]float64)
data["red"] = 1.00
data["green"] = 3.00
data["blue"] = 2.00
I tried the following, but that only sorts by the string
in the map, not the actual float64
:我尝试了以下操作,但仅按地图中的
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])
}
It expects int
instead of float64
because i, j
are indices to use on comparing and swapping elements in a slice.它需要
int
而不是float64
因为i, j
是用于比较和交换切片中元素的索引。 I recommend you should use a new struct and implement the sort.Interface for it:我建议你应该使用一个新的结构并为它实现 sort.Interface:
type MapData struct {
Key string
Value float64
}
type MapSort []*MapData
func (m MapSort) Len() int {
return len(m)
}
func (m MapSort) Less(i, j int) bool {
return m[i].Value < m[j].Value
}
func (m MapSort) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
Thanks to Marc for pointing out my mistake, here's what I'm using to sort successfully:感谢 Marc 指出我的错误,这是我用来成功排序的方法:
package main
import (
"fmt"
"math"
"sort"
)
// round a float64 to 2 decimal places.
func round(n float64) float64 {
return math.Round(n*100) / 100
}
type Pair struct {
Key string
Value float64
}
type PairList []Pair
func (p PairList) Len() int { 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) { p[i], p[j] = p[j], p[i] }
func main() {
data := make(map[string]float64)
data["red"] = 1.00
data["green"] = 3.00
data["blue"] = 2.00
var i int
sorted := make(PairList, len(data))
for key, value := range data {
sorted[i] = Pair{key, value}
i++
}
sort.Sort(sort.Reverse(sorted))
for _, pair := range sorted {
fmt.Printf("%s %v\n", pair.Key, round(pair.Value))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.