Swa*_*wal 1 arrays sorting maps go
我刚刚开始在Golang中编程,想对地图数组进行排序。我有一系列的地图。我们称之为example_array。
example_array = [
[
{ Name: "A", Value: 100 },
{ Name: "B", Value: 60 },
{ Name: "C", Value: 170 },
{ Name: "D", Value: 120}
],
[
{ Name: "A", Value: 64 },
{ Name: "B", Value: 90 },
{ Name: "C", Value: 52 },
{ Name: "D", Value: 98}
],
[
{ Name: "A", Value: 154 },
{ Name: "B", Value: 190 },
{ Name: "C", Value: 179 },
{ Name: "D", Value: 67 }
]
Run Code Online (Sandbox Code Playgroud)
]
现在我想使用key的值对该数组进行排序,"C"因此example_array应该修改为->
[
[{Name: "A", Value: 64}, {Name: "B", Value: 90}, {Name: "C", Value: 52}, {Name: "D", Value: 98}],
[{Name: "A", Value: 100}, {Name: "B", Value: 60}, {Name: "C", Value: 170}, {Name: "D", Value: 120}],
[{Name: "A", Value: 154}, {Name: "B", Value: 190}, {Name: "C", Value: 179}, {Name: "D", Value: 67}]
]
Run Code Online (Sandbox Code Playgroud)
如果我使用key的值对原始数组进行排序"D",则应将原始数组修改为->
[
[{Name: "A", Value: 154}, {Name: "B", Value: 190}, {Name: "C", Value: 179}, {Name: "D", Value: 67}],
[{Name: "A", Value: 64}, {Name: "B", Value: 90}, {Name: "C", Value: 52}, {Name: "D", Value: 98}]
[{Name: "A", Value: 100}, {Name: "B", Value: 60}, {Name: "C", Value: 170}, {Name: "D", Value: 120}]
]
Run Code Online (Sandbox Code Playgroud)
如何在Golang中对这些地图数组进行排序。请帮忙!
您的数据看起来很容易表示为type of map的一部分map[string]int。由于您没有在问题中提供任何Go代码,因此我不确定数据类型,因此我将假定它是map[string]int此答案中类型的映射的一部分。
A simple way to sort a slice of maps is to use the sort.Slice function. From a comment in the first example in the sort package documentation:
use
sort.Slicewith a custom Less function, which can be provided as a closure. In this case no methods are needed
The Less function needs to satisfy the signature
func(i, j int) bool
Run Code Online (Sandbox Code Playgroud)
Per package documentation (at Interface):
Less reports whether the element with index
ishould sort before the element with indexj.
Using a closure allows you to reference your data structure in the function body even though it is not part of the parameter list.
Here's a runnable example that sorts a slice of map[string]int values matching the data in your question:
package main
import(
"fmt"
"sort"
)
func main() {
in := []map[string]int{
{
"A": 100,
"B": 60,
"C": 170,
"D": 120,
},
{
"A": 64,
"B": 90,
"C": 52,
"D": 98,
},
{
"A": 154,
"B": 190,
"C": 179,
"D": 67,
},
}
for k, _ := range in[0] {
sort.Slice(in, func(i, j int) bool { return in[i][k] < in[j][k] })
fmt.Printf("By %s: %v\n", k, in)
}
}
Run Code Online (Sandbox Code Playgroud)
Output:
By A: [map[A:64 B:90 C:52 D:98] map[A:100 B:60 C:170 D:120] map[A:154 B:190 C:179 D:67]]
By B: [map[A:100 B:60 C:170 D:120] map[B:90 C:52 D:98 A:64] map[C:179 D:67 A:154 B:190]]
By C: [map[A:64 B:90 C:52 D:98] map[A:100 B:60 C:170 D:120] map[A:154 B:190 C:179 D:67]]
By D: [map[A:154 B:190 C:179 D:67] map[B:90 C:52 D:98 A:64] map[A:100 B:60 C:170 D:120]]
Run Code Online (Sandbox Code Playgroud)