sorting - 在 GoLang 中排序对

标签 sorting go key key-value

我知道如何根据数据类型对键/值进行排序:

map[1:a 2:c 0:b]

使用 GoLang 的 sort 包。我如何对 Pair 进行排序,如下所示:

[{c 2} {a 1} {b 0}]

我希望整对根据键或值排序?最终结果:

[{a 1} {b 0} {c 2}]

这是根据键排序的。以下是根据值排序:

[{b 0} {a 1} {c 2}]

最佳答案

您可以为自定义类型实现 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 by Key
    sort.Sort(ByKey(pairs))
    fmt.Println(pairs) // [{a 1} {b 0} {c 2}]
}

关于sorting - 在 GoLang 中排序对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693708/

相关文章:

node.js - 将 id 从 json 响应映射到 key 并将其用于 FlatList React-native

sorting - 如何使用 Gremlin 对 Noe4j 结果进行排序和限制?

database - Golang worker 池导致数据库损坏

Go 服务器听不到远程请求

go - 为什么当我将 `opencv.NewWindow()` 移动到子函数时我的程序立即终止?

python - 检查某个键不存在

java - 如何覆盖TreeMap中的值?

Java 比较数组中的字符串

php - 如何在 Magento 中对集合进行排序?

shell - 按行上的字数对海量文件的行进行排序(最好是并行的)