go map数据结构

map数据结构

key-value的数据结构,又叫字典或关联数组

  • 声明:
var map1 map[keytype]valuetype
var a map[string]string
var a map[string]int
var a map[int]string
var a map[string]map[string]string

备注:声明是不会分配内存的,初始化需要make

样例一:

func testMap() {
    var a map[string]string
    a = make(map[string]string, 10)
    a["abc"] = "efg"
    a["abc"] = "efg"
    a["abc1"] = "efg"
    fmt.Println(a)
}

样例二:

func testMap() {
    a := make(map[string]string, 10)
    a["abc"] = "efg"
    a["abc"] = "efg"
    a["abc1"] = "efg"
    fmt.Println(a)
}

样例三:

func testMap() {
	var a map[string]string = map[string]string{
		"key": "value",
	}
	a["abc"] = "efg"
	a["abc"] = "efg"
	a["abc1"] = "efg"
	fmt.Println(a)
}

 

  • map相关操作
var a map[string]string = map[string]string{"hello": "world"}
a = make(map[string]string, 10)

插入和更新:a[“hello”] = “world”

查找:Val, ok := a[“hello”]

遍历:

for k, v := range a { 
    fmt.Println(k,v) 
}

删除:delete(a, “hello”)

长度:len(a)

func trans(a map[string]map[string]string) {
	for k, v := range a {
		fmt.Println(k)
		for k1, v1 := range v {
			fmt.Println("\t", k1, v1)
		}
	}
}

func testMap4() {
	a := make(map[string]map[string]string, 100)
	a["key1"] = make(map[string]string)
	a["key1"]["key2"] = "abc"
	a["key1"]["key3"] = "abc"
	a["key1"]["key4"] = "abc"
	a["key1"]["key5"] = "abc"

	a["key2"] = make(map[string]string)
	a["key2"]["key2"] = "abc"
	a["key2"]["key3"] = "abc"

	trans(a)
	delete(a, "key1")
	fmt.Println()
	trans(a)
	fmt.Println(len(a))
}

 

  • 多层map
func testMap2() {
	a := make(map[string]map[string]string, 100)
	a["key1"] = make(map[string]string)
	a["key1"]["key2"] = "abc"
	a["key1"]["key3"] = "abc"
	a["key1"]["key4"] = "abc"
	a["key1"]["key5"] = "abc"
	fmt.Println(a)
}

 

  • slice of map
func testMapSlice() {
   s := make([]map[string]int, 10)
   for i := 0; i < len(s); i++ {
      s[i] = make(map[string]int, 100)
   }
   s[0]["abc"] = 100
   s[0]["qwe"] = 100
   s[5]["abc"] = 100
   fmt.Println(s)
}

备注:上面第一次make是切片的长度,第二次make是map的容量

 

  • map排序

a. 先获取所有key,把key进行排序

b. 按照排序好的key,进行遍历

func testMapSort() {
	var a map[int]int
	a = make(map[int]int, 5)

	a[8] = 10
	a[3] = 10
	a[2] = 10
	a[1] = 10
	a[18] = 10

	var keys []int
	for k, _ := range a {
		keys = append(keys, k)
		//fmt.Println(k, v)
	}

	sort.Ints(keys)

	for _, v := range keys {
		fmt.Println(v, a[v])
	}
}

 

  • map反转

初始化另外一个map,把key、value互换即可

func test() {
	var a map[string]int
	var b map[int]string

	a = make(map[string]int, 5)
	b = make(map[int]string, 5)

	a["abc"] = 101
	a["efg"] = 10

	fmt.Println(a)

	for k, v := range a {
		b[v] = k
	}

	fmt.Println(b)
}

 

posted @ 2017-08-29 10:16  shhnwangjian  阅读(431)  评论(0编辑  收藏  举报