Sort pair in GoLang

huangapple go评论98阅读模式
英文:

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

你可以为自定义类型实现LenSwapLess方法。这里有一个示例: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 (
    &quot;fmt&quot;
    &quot;sort&quot;
)

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 &lt; s[j].Key
}

func main() {
    pairs := []Pair{{&quot;a&quot;, 1}, {&quot;b&quot;, 0}, {&quot;c&quot;, 2}}
    // Sort by Key
    sort.Sort(ByKey(pairs))
    fmt.Println(pairs) // [{a 1} {b 0} {c 2}]
}

huangapple
  • 本文由 发表于 2015年4月17日 16:09:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/29693708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定