映射 – Map

数据类型 Liemer_Lius 873℃

定义:映射是存储一系列无序的key/value对,通过key来对value进行操作(增、删、改、查)。
Map是无序的。

key/value规则:

映射的key只能为可使用==运算符的值类型(字符串、数字、布尔、数组),value可以是任意的类型。

定义、赋值:

scores := make(map[string]int, 0)  // make来定义
scores["Alice"] = 12
fmt.Println(scores) // map[Alice:12]
scores := map[string]int{"Liemer": 1, "Lius": 100} // 字面量来定义, map[Liemer:1 Lius:100]

操作:

// 增
scores["hello"] = 12 // 如果没有元素就新增

// 删
delete(scores, "Lius")

// 改
scores["Lius"] = 3 // map[Liemer:1 Lius:3]

// 查:如果key不存在,默认取零值,所以,需要判定一下
scores := map[string]int{"Liemer": 1, "Lius": 100}
fmt.Println(scores["Lius"]) // 100
fmt.Println(scores["Tom"])  // 0, 不存在,取零值
if v, ok := scores["Tom"]; ok {
	fmt.Println(v)
} else {
    fmt.Println(ok) // false
	fmt.Println("Tom does not exist...") // Tom does not exist...
}

长度:len

fmt.Println(len(scores))

for range:

for k, _ := range scores {
	fmt.Printf("Key: %v; Value: %v\n", k, scores[k])
}
Key: Lius; Value: 100
Key: Liemer; Value: 1

投票:Exp1

ticket := []string{"Tom", "Jerry", "Alice", "Jerry", "Tom"}
scores := map[string]int{}
for _, n := range ticket {
	scores[n] += 1
}
fmt.Println(scores) // map[Alice:1 Jerry:2 Tom:2]

大小写英文字母统计【加排序】:Exp2

func main() {
	art_map := map[rune]int{}
	article := `Package os provides a platform-independent interface to operating system functionality.
The design is Unix-like, although the error handling is Go-like; failing calls return values
of type error rather than error numbers. Often, more information is available within
the error. For example, if a call that takes a file name fails, such as Open or Stat,
the error will include the failing file name when printed and will be of type *PathError,
which may be unpacked for more information.`
	art_rune := []rune(article)
	for _, v := range art_rune {
		if v >= 'A' && v <= 'Z' || v >= 'a' && v <= 'z' {
			art_map[v] += 1
		}
	}

	idx_slice := []int{}
	for k, _ := range art_map {
		idx_slice = append(idx_slice, int(k))
	}
	sort.Ints(idx_slice) // 排序一下

	for _, v := range idx_slice {

		fmt.Printf("%c: %v; ", rune(v), art_map[rune(v)])
	}
	fmt.Println()
}

# go run main.go
E: 1; F: 1; G: 1; O: 2; P: 2; S: 1; T: 1; U: 1; a: 35; b: 4; c: 9; d: 9; e: 46; f: 15; g: 7; h: 17; i: 34; k: 5; l: 24; m: 11; n: 30; o: 25; p: 10; r: 35; s: 15; t: 29; u: 8; v: 3; w: 5; x: 2; y: 5;

 

 

 

 

 

 

 

 

转载请注明:liutianfeng.com » 映射 – Map

喜欢 (2)

评论已关闭。