我们知道,在golang中map
类型的键值key/value
都是无序排列的,这篇博客讨论一部分我在学习语法过程中思考的排序的方法
这里我们考虑下面这种map如何按照数字大小排序输出?
map1["Mon"]=1
map1["Tue"]=2
map1["Wed"]=3
map1["Thu"]=4
map1["Fri"]=5
map1["Sat"]=6
map1["Sun"]=7
首先将key/value
拷贝进一个切片,对切片调用sort
包进行排序
教程中采用的是map[string]int
类型,将string
进行字母排序后输出即可
我们思考一下:如果是对int
进行排序呢?我们将int赋值给一个切片value
以一个星期每天为例:
//拷贝到切片后排序结果
value[0]=1
value[1]=2
value[2]=3
......
//但是将int排序后很难再去map中找其对应的string
但是将int
排序后很难再去map
中找其对应的string
,就好比我们知道数组每一个位置对应的数值,但是知道这个数值难以反推回对应是第几个数对吧?
于是再循环一次map
,判断哪个string
对应按顺序排列的int
(多一次循环&判断)
package main
import "fmt"
import "sort"
func main() {
map1 := make(map[string]int)
map1["Mon"]=1
map1["Tue"]=2
map1["Wed"]=3
map1["Thu"]=4
map1["Fri"]=5
map1["Sat"]=6
map1["Sun"]=7
fmt.Println("unsorted:")
for key,val := range map1{
fmt.Printf("%s is the %d of a week
",key,val)
}
fmt.Println("sorted:")
value := make([]int,len(map1))
i := 0
for _,val := range map1{
value[i]=val
i++
}
sort.Ints(value)
for i,_ := range value{
for j := range map1{
if map1[j]== value[i]{
fmt.Printf("%s is the %d of a week
",j,value[i])
}
}
}
}
output:
unsorted:
Wed is the 3 of a week
Thu is the 4 of a week
Fri is the 5 of a week
Sat is the 6 of a week
Sun is the 7 of a week
Mon is the 1 of a week
Tue is the 2 of a week
sorted:
Mon is the 1 of a week
Tue is the 2 of a week
Wed is the 3 of a week
Thu is the 4 of a week
Fri is the 5 of a week
Sat is the 6 of a week
Sun is the 7 of a week
这样双重循环加判断是个方法,我们也可以采用另一种方法:先交换键值,然后排序!
package main
import "fmt"
func main() {
map1 := make(map[string]int)
map1["Mon"]=1
map1["Tue"]=2
map1["Wed"]=3
map1["Thu"]=4
map1["Fri"]=5
map1["Sat"]=6
map1["Sun"]=7
invMap := make(map[int]string,len(map1))
for k,v := range map1{
invMap[v]=k
}
fmt.Println("inverted:")
for k,v := range invMap{
fmt.Printf("The %d day is %s
",k,v)
}
}
当然这个时候发现,我们再用map
对key
排序方法对数字进行排序,输出对应字符串也就非常方便了!
package main
import "fmt"
import "sort"
func main() {
map1 := make(map[string]int)
map1["Mon"]=1
map1["Tue"]=2
map1["Wed"]=3
map1["Thu"]=4
map1["Fri"]=5
map1["Sat"]=6
map1["Sun"]=7
invMap := make(map[int]string,len(map1))
for k,v := range map1{
invMap[v]=k
}
fmt.Println("inverted:")
for k,v := range invMap{
fmt.Printf("The %d day is %s
",k,v)
}
fmt.Println("inverted and sorted:")
value := make([]int,len(invMap))
i := 0
for val,_ := range invMap{
value[i]=val
i++
}
sort.Ints(value)
for _,j := range value{
fmt.Printf("The %d day is %s
",j,invMap[j])
}
}
output:
inverted:
The 6 day is Sat
The 7 day is Sun
The 1 day is Mon
The 2 day is Tue
The 3 day is Wed
The 4 day is Thu
The 5 day is Fri
inverted and sorted:
The 1 day is Mon
The 2 day is Tue
The 3 day is Wed
The 4 day is Thu
The 5 day is Fri
The 6 day is Sat
The 7 day is Sun
这样也就实现了对数字的排序Bingo!