Files
the-way-to-go_ZH_CN/eBook/08.5.md
Guobiao Mei 07d26e14d1 Fix links to the code examples
Change-Id: I644c6a516abab2577353644c128102457deeb41a
2014-12-18 16:49:46 -05:00

60 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#8.5 map排序
map默认是无序的不管是按照key还是按照value默认都不排序参见8.3节)
如果你想为map排序需要将key或者value拷贝到一个slice再对slice排序使用sort包参见7.6.6然后可以使用slice的for-range方法打印出所有的key和value。
下面有一个示例:
示例 8.6 [sort_map.go](examples/chapter_8/sort_map.go)
// the telephone alphabet:
package main
import (
"fmt"
"sort"
)
var (
barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23,
"delta": 87, "echo": 56, "foxtrot": 12,
"golf": 34, "hotel": 16, "indio": 87,
"juliet": 65, "kili": 43, "lima": 98}
)
func main() {
fmt.Println("unsorted:")
for k, v := range barVal {
fmt.Printf("Key: %v, Value: %v / ", k, v)
}
keys := make([]string, len(barVal))
i := 0
for k, _ := range barVal {
keys[i] = k
i++
}
sort.Strings(keys)
fmt.Println()
fmt.Println("sorted:")
for _, k := range keys {
fmt.Printf("Key: %v, Value: %v / ", k, barVal[k])
}
}
输出结果:
unsorted:
Key: bravo, Value: 56 / Key: echo, Value: 56 / Key: indio, Value: 87 / Key: juliet, Value: 65 / Key: alpha, Value: 34 / Key: charlie, Value: 23 / Key: delta, Value: 87 / Key: foxtrot, Value: 12 / Key: golf, Value: 34 / Key: hotel, Value: 16 / Key: kili, Value: 43 / Key: lima, Value: 98 /
sorted:
Key: alpha, Value: 34 / Key: bravo, Value: 56 / Key: charlie, Value: 23 / Key: delta, Value: 87 / Key: echo, Value: 56 / Key: foxtrot, Value: 12 / Key: golf, Value: 34 / Key: hotel, Value: 16 / Key: indio, Value: 87 / Key: juliet, Value: 65 / Key: kili, Value: 43 / Key: lima, Value: 98 / [fangjun@st01-dstream-0001.st01.baidu.com go]$ sz -be sort_map.go
但是如果你想要一个排序的列表你最好使用结构体slice这样会更有效
type struct {
key string
value int
}
##链接
- [目录](directory.md)
- 上一节:[maps分片](08.4.md)
- 下一节:[倒置map](08.6.md)