mapkey/value
这里我们考虑下面这种map如何按照数字大小排序输出?
map1["Mon"]=1
map1["Tue"]=2
map1["Wed"]=3
map1["Thu"]=4
map1["Fri"]=5
map1["Sat"]=6
map1["Sun"]=7
key/valuesortmap[string]intstringintvalue
//拷贝到切片后排序结果
value[0]=1
value[1]=2
value[2]=3
......
//但是将int排序后很难再去map中找其对应的string
intmapstring
mapstringint
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)
}
}
mapkey
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!