mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 00:43:26 +08:00
add 08.2.md 08.3.md 08.4.md 08.5.md 08.6.md
This commit is contained in:
44
eBook/08.6.md
Normal file
44
eBook/08.6.md
Normal file
@@ -0,0 +1,44 @@
|
||||
#8.6 倒置map
|
||||
这里倒置是指调换key和value。如果map的值类型可以作为key且所有的value是唯一的,那么通过下面的方法可以简单的做到倒置:
|
||||
|
||||
示例 8.7 [invert_map.go](exmaples/chapter_8/invert_map.go)
|
||||
|
||||
package main
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
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() {
|
||||
invMap := make(map[int]string, len(barVal))
|
||||
for k, v := range barVal {
|
||||
invMap[v] = k
|
||||
}
|
||||
fmt.Println("inverted:")
|
||||
for k, v := range invMap {
|
||||
fmt.Printf("Key: %v, Value: %v / ", k, v)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
输出结果:
|
||||
|
||||
inverted:
|
||||
Key: 34, Value: golf / Key: 23, Value: charlie / Key: 16, Value: hotel / Key: 87, Value: delta / Key: 98, Value: lima / Key: 12, Value: foxtrot / Key: 43, Value: kili / Key: 56, Value: bravo / Key: 65, Value: juliet /
|
||||
|
||||
如果原始value值不唯一那么这么做肯定会出错;为了保证不出错,当遇到不唯一的key时应当立刻停止,这样可能会导致没有包含原map的所有键值对!一种解决方法就是仔细检查唯一性并且使用多值map,比如使用`map[int][]string`类型。
|
||||
|
||||
练习 8.2: map_drinks.go
|
||||
|
||||
构造一个将英文饮料名映射为法语(或者任意你的母语)的集合;先打印所有的饮料,然后打印原名和翻译后的名字。接下来按照英文名排序后再打印出来。
|
||||
|
||||
##链接
|
||||
- [目录](directory.md)
|
||||
- 上一节:[map排序](08.5.md)
|
||||
- 下一节:[包](09.0.md)
|
Reference in New Issue
Block a user