go映射的定义和增删改(27)

2023年 7月 15日 28.4k 0

请输入图片描述

key和value通过某一种关系,在访问的时候通过key访问value,而映射存储的就是key,value结构(映射是存储一系列无序的key/value对),通过key对value进行查询。

  • key/value规则

映射的key只能为可使用==运算符的值类型(字符串,数字,布尔,数组),因为key至少要进行判断,value可以为任何类型

7.1定义一个映射

使用map定义,可以定义key是运算符的值任何value类型,如:[]括号内是key的类型,值是int类型的映射,如下:

var scores map[string]int
[root@www.linuxea.com_1 /opt/Golang/work2]# cat map.go
package main
import "fmt"
func main(){

    var scores map[string]int
    
    fmt.Printf("%T %vn",scores,scores)
    fmt.Println(scores == nil)
}

打印

[root@www.linuxea.com_1 /opt/Golang/work2]go run map.go 
map[string]int map[]
true

如果映射会nil,是不能进行操作的

7.2映射字面量

可以直接使用map定义

scores = map[string]int{}

{}空,就没有值。

假如输入"mark":2,"marksugar":3,进行初始化

    scores = map[string]int{"mark":2,"marksugar":3}
    fmt.Println(scores)

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go
map[mark:2 marksugar:3]

也可以使用make,如:make(map[string]int{}),也是空值。和scores = map[string]int{}一样

7.3映射的增删改查

查找mark的,使用scores["mark"]即可

fmt.Println(scores["mark"])

运行得到的value是2

[root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go
2

在映射中如果访问一个不存在的key结果将会返回对应value的0值。

在key访问的时候,可以通过返回值来进行判断存在与否。如下:

     _,ok := scores["sean"]
    if ok{
        fmt.Println(scores["sean"])
    }else{
        fmt.Println("不存在")
    }

这种写法的简写如下

   if _,ok := scores["sean"];ok{
       fmt.Println(scores["sean"])
   }else{
       fmt.Println("不存在")
   }

如果为true则说明存在,如果是false说明不存在。运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go 
不存在
  • 修改

直接重新赋值,此刻修改mark的value等于10:scores["mark"] = 10

    fmt.Println("mark:",scores["mark"])
    scores["mark"] = 10
    fmt.Println("mark:",scores["mark"])
[root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go 
mark: 2
mark: 10

如果赋值一个不存在的key的值将会添加。如果存在则是修改。

  • 删除

假如此时删除mark,直接使用delete(scores,"mark")即可

    fmt.Println(scores)
    delete(scores,"mark")
    fmt.Println(scores)

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go
map[mark:10 marksugar:3]
map[marksugar:3]
  • 添加

在将mark添加 回来:scores["mark"] = 66

    scores["mark"] = 66
    fmt.Println(scores)

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go 
map[mark:66 marksugar:3]

增删改查代码块

package main
import "fmt"
func main(){

    var scores map[string]int
    
    fmt.Printf("%T %vn",scores,scores)
    fmt.Println(scores == nil)

    scores = map[string]int{"mark":2,"marksugar":3}
    fmt.Println(scores)

    fmt.Println(scores["mark"])

    if  _,ok := scores["sean"];ok{
        fmt.Println(scores["sean"])
    }else{
        fmt.Println("不存在")
    }

    if _,ok := scores["marksugar"];ok{
        fmt.Println(scores["marksugar"])
    }else{
        fmt.Println("不存在")
    }
    fmt.Println("mark:",scores["mark"])
    scores["mark"] = 10
    fmt.Println("mark:",scores["mark"])

    fmt.Println(scores)
    delete(scores,"mark")
    fmt.Println(scores)

    scores["mark"] = 66
    fmt.Println(scores)
}

7.4映射的长度获取

使用len即可,如:len(scores)

7.5遍历映射

直接可以使用for rage进行遍历,但是遍历结果顺序和添加的顺序是没有关系的。因为映射是无序的,这和映射hash有关。如遍历scores

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

结果

root@www.linuxea.com_1 /opt/Golang/work2]# go run map.go
mark 66
marksugar 3

7.6定义映射的映射

如果现在要定义一个映射,格式是: 映射[字符串]字符串{"地址","电话",”身高“}。那么格式如下:

var users map[string]map[string]string

在进行初始化

users = map[string]map[string]string{"mark":{"地址":"上海","电话":"10086","身高":"一米八"}}

打印

fmt.Printf("%T,%vn",users,users)

如下:

#go run map2.go
map[string]map[string]string,map[mark:map[地址:上海 电话:10086 身高:一米八]]
  • 增删改查

添加一个sean

    users["sean"] = map[string]string{"地址":"上海","电话":"10086","身高":"一米八"}
    fmt.Printf("%T,%vn",users,users)

而后修改mark的地址和身高

    users["mark"] = map[string]string{"地址":"上海","电话":"10086","身高":"1.9"}
    users["mark"]["地址"] = "北京"
    fmt.Printf("%T,%vn",users,users)

而后在删除mark字段的电话

    delete(users["mark"],"电话")
    fmt.Printf("%T,%vn",users,users)

代码块

package main
import "fmt"
func main(){
    var users map[string]map[string]string
    users = map[string]map[string]string{"mark":{"地址":"上海","电话":"10086","身高":"一米八"}}
    fmt.Printf("%T,%vn",users,users)

    users["sean"] = map[string]string{"地址":"上海","电话":"10086","身高":"一米八"}
    fmt.Printf("%T,%vn",users,users)

    users["mark"] = map[string]string{"地址":"上海","电话":"10086","身高":"1.9"}
    users["mark"]["地址"] = "北京"
    fmt.Printf("%T,%vn",users,users)

    delete(users["mark"],"电话")
    fmt.Printf("%T,%vn",users,users)
}

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run map2.go
map[string]map[string]string,map[mark:map[地址:上海 电话:10086 身高:一米八]]
map[string]map[string]string,map[mark:map[地址:上海 电话:10086 身高:一米八] sean:map[地址:上海 电话:10086 身高:一米八]]
map[string]map[string]string,map[mark:map[地址:北京 电话:10086 身高:1.9] sean:map[地址:上海 电话:10086 身高:一米八]]
map[string]map[string]string,map[mark:map[地址:北京 身高:1.9] sean:map[地址:上海 电话:10086 身高:一米八]]

7.7练习题1

  • 统计映射内字段出现的次数

1.统计以下字符串出现的次数

users := []string{"mark","sean","mark","edwin","mark","justin"}

示例:

首先,key是string,value是int的映射

user_stat := make(map[string]int)

而后使用for range遍历users,使用if判断遍历的结果,如果为true,也就是存在就就加1,否则赋值等于1,添加到user_stat映射中

    for _,user := range users {
        if _,ok := user_stat[user];ok{
            user_stat[user]++
        }else {
            user_stat[user] =1
        }
    }

而后打印user_statfmt.Println(user_stat)

代码块

[root@www.linuxea.com_1 /opt/Golang/work2]# cat work1.go
package main
import "fmt"
func main(){
    users := []string{"mark","sean","mark","edwin","mark","justin"}

    user_stat := make(map[string]int)

    for _,user := range users {
        if _,ok := user_stat[user];ok{
            user_stat[user]++
        }else {
            user_stat[user] =1
        }
    }
    fmt.Println(user_stat)
}

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run work1.go 
map[edwin:1 justin:1 mark:3 sean:1]

这段代码可以进行简化。在go的映射中如果值不存在返回是0,那就可以直接进行++。逻辑就成了,如果遍历一次就加一次。如果值不存在就成了1+0,如果存在就会继续相加

[root@www.linuxea.com_1 /opt/Golang/work2]# cat work1.go
package main
import "fmt"
func main(){
    users := []string{"mark","sean","mark","edwin","mark","justin"}

    user_stat := make(map[string]int)

    for _,user := range users {
        user_stat[user]++
    }
    fmt.Println(user_stat)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work2.go 
map[edwin:1 justin:1 mark:3 sean:1]

7.8练习题2

  • 统计文章内字母出现的次数

示例:我从github找了一段,声明article

article := `Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution.""Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.`

而后定义一个映射key是rune,value是int

article_stat := map[rune]int{}

而后遍历article,遍历的value,如果值小于等于A,大于等于Z。并且大于等于a,小于等于z,就将值加1。代码块如下:

    for _,ch := range article {
        if ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' {
            article_stat[ch]++
        }
    }

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run work3.go
map[67:12 68:3 69:2 70:1 71:2 73:1 76:12 78:1 79:1 80:1 83:3 87:14 89:4 97:117 98:45 99:81 100:53 101:193 102:36 103:31 104:73 105:178 106:3 107:18 108:69 109:36 110:160 111:177 112:35 113:1 114:142 115:111 116:197 117:66 118:18 119:20 120:4 121:39 122:1]

为了更方便查看,遍历article_stat,打印出key和value

    for ch,cnt := range article_stat {
        fmt.Printf("%c:%dn",ch,cnt)
    }

完整的代码块

[root@www.linuxea.com_1 /opt/Golang/work2]# cat work3.go
package main
import "fmt"
func main(){

   article := `Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution.""Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.`

    article_stat := map[rune]int{}

    for _,ch := range article {
        if ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' {
            article_stat[ch]++
        }
    }
    fmt.Println(article_stat)
    for ch,cnt := range article_stat {
        fmt.Printf("%c:%dn",ch,cnt)
    }
}

运行

[root@www.linuxea.com_1 /opt/Golang/work2]# go run work3.go
map[67:12 68:3 69:2 70:1 71:2 73:1 76:12 78:1 79:1 80:1 83:3 87:14 89:4 97:117 98:45 99:81 100:53 101:193 102:36 103:31 104:73 105:178 106:3 107:18 108:69 109:36 110:160 111:177 112:35 113:1 114:142 115:111 116:197 117:66 118:18 119:20 120:4 121:39 122:1]
E:2
F:1
d:53
v:18
W:14
L:12
C:12
i:178
c:81
G:2
I:1
o:177
r:142
m:36
z:1
x:4
w:20
k:18
N:1
j:3
s:111
h:73
y:39
n:160
p:35
S:3
D:3
q:1
Y:4
P:1
u:66
a:117
e:193
f:36
g:31
O:1
t:197
b:45
l:69

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论