英文:
Sort pair in GoLang
问题
我知道如何使用Go语言的sort
包对具有数据类型的键/值进行排序:
map[1:a 2:c 0:b]
要如何对以下形式的Pair
进行排序:
[{c 2} {a 1} {b 0}]
我希望整个键值对可以按照键或值进行排序。最终结果应该是:
按照键排序的结果:
[{a 1} {b 0} {c 2}]
按照值排序的结果:
[{b 0} {a 1} {c 2}]
英文:
I know how to sort key/value with data type:
map[1:a 2:c 0:b]
using sort
package of GoLang. How can I sort a Pair
like the following:
[{c 2} {a 1} {b 0}]
I want the whole pair to be sorted either according to key or value? End result:
[{a 1} {b 0} {c 2}]
this is sorted according to keys. Below is sorted according to values:
[{b 0} {a 1} {c 2}]
答案1
得分: 4
你可以为自定义类型实现Len
、Swap
和Less
方法。这里有一个示例:https://gobyexample.com/sorting-by-functions
以下是如何按键排序的示例:http://play.golang.org/p/i6-e4I7vih
import (
"fmt"
"sort"
)
type Pair struct {
Key string
Value int
}
type ByKey []Pair
func (s ByKey) Len() int {
return len(s)
}
func (s ByKey) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByKey) Less(i, j int) bool {
return s[i].Key < s[j].Key
}
func main() {
pairs := []Pair{{"a", 1}, {"b", 0}, {"c", 2}}
// 按键排序
sort.Sort(ByKey(pairs))
fmt.Println(pairs) // [{a 1} {b 0} {c 2}]
}
希望对你有帮助!
英文:
You could implement Len
, Swap
and Less
for a custom type. An example is given here: https://gobyexample.com/sorting-by-functions
Here's how you could sort by key for your example: http://play.golang.org/p/i6-e4I7vih
import (
"fmt"
"sort"
)
type Pair struct {
Key string
Value int
}
type ByKey []Pair
func (s ByKey) Len() int {
return len(s)
}
func (s ByKey) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByKey) Less(i, j int) bool {
return s[i].Key < s[j].Key
}
func main() {
pairs := []Pair{{"a", 1}, {"b", 0}, {"c", 2}}
// Sort by Key
sort.Sort(ByKey(pairs))
fmt.Println(pairs) // [{a 1} {b 0} {c 2}]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论