1 回答
TA贡献1876条经验 获得超6个赞
您无法对map
.
将 转换
map
为键值对结构的切片。对切片进行排序(另请参见如何使用多个排序参数对结构进行排序?)
例如像这样:
func main() {
wordFrequency := map[string]int{"banana": 3, "america": 2, "abb": 2, "test": 2, "car": 1}
vec := mapToSlice(wordFrequency)
sort.Slice(vec, func(i, j int) bool {
// 1. value is different - sort by value (in reverse order)
if vec[i].value != vec[j].value {
return vec[i].value > vec[j].value
}
// 2. only when value is the same - sort by key
return vec[i].key < vec[j].key
})
fmt.Printf("%v", vec)
}
func mapToSlice(in map[string]int) []KV {
vec := make([]KV, len(in))
i := 0
for k, v := range in {
vec[i].key = k
vec[i].value = v
i++
}
return vec
}
type KV struct {
key string
value int
}
印刷:
[{banana 3} {abb 2} {america 2} {test 2} {car 1}]
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报