2 回答

TA貢獻1880條經驗 獲得超4個贊
它期望int而不是float64因為i, j是用于比較和交換切片中的元素的索引。我建議你應該使用一個新的結構并為它實現 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]
}

TA貢獻1815條經驗 獲得超13個贊
這是我用來成功排序的內容:
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))
}
}
- 2 回答
- 0 關注
- 157 瀏覽
添加回答
舉報