查看上一篇接口类型请点我
golang中的map就相当于python中的dict,key:value形式,无序,key唯一。
1.map的创建和增删改查
废话少说,上例子:
package main
import "fmt"
func main() {
people := make(map[string]string)
people["name"] = "houyuming"
fmt.Println(people["name"])
animal := map[string]string{
"name": "houyuming",
"sex": "man",
}
fmt.Println(animal)
//2.map的增删改查--增
animal["age"] = "18"
fmt.Println(animal)
//2.map的增删改查--删
delete(animal, "age")
fmt.Println(animal)
//2.map的增删改查--改(golang的map是引用类型,两个map同时指向同一个底层,修改其中一个,另一个也会改变(深拷贝))
animal["sex"] = "human"
fmt.Println(animal)
//2.map的增删改查--查
fmt.Println(animal["name"])
fmt.Println(animal["age"])
for k, v := range animal{
fmt.Println(k, v)
}
}
运行结果:
houyuming
map[name:houyuming sex:man]
map[age:18 name:houyuming sex:man]
map[name:houyuming sex:man]
map[name:houyuming sex:human]
houyuming
name houyuming
sex human
2.判断map中是否存在某个key
package main
import "fmt"
func main() {
animal := map[string]string{
"name": "houyuming",
"sex": "man",
}
fmt.Println(animal)
if v, ok := animal["name"]; ok {
fmt.Println("存在key=",v)
}else {
fmt.Println("没有找到key=",v)
}
}
运行结果:
map[name:houyuming sex:man]
存在key= houyuming
3.map排序
1).根据key排序
package main
import (
"fmt"
"sort"
)
func main() {
animal := map[string]int{
"d": 3,
"a": 2,
"c": 1,
"b": 4,
}
fmt.Println(animal)
arr := []string{}
for k := range animal{
arr = append(arr, k)
}
fmt.Println(arr)
sort.Strings(arr)
fmt.Println(arr)
for _, key := range arr{
fmt.Println(key, animal[key])
}
}
运行结果:
map[a:2 b:4 c:1 d:3]
[d a c b]
[a b c d]
a 2
b 4
c 1
d 3
2).根据value排序
思路是直接不用map,用struct存放key和value,实现sort接口,就可以调用sort.Sort进行排序了
package main
import (
"fmt"
"sort"
)
type Pair struct {
Key string
Value int
}
type PairList []Pair
func (p PairList) Swap(i, j int){
p[i], p[j] = p[j], p[i]
}
func (p PairList) Len() int{
return len(p)
}
func (p PairList) Less(i, j int) bool{
return p[i].Value < p[j].Value
}
func main() {
m := map[string]int{
"a":18,
"b":16,
"c":21,
"d":35,
"e":23,
}
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
i ++
}
sort.Sort(p)
fmt.Println(p)
for _,a := range p{
fmt.Println(a.Key, a.Value)
}
}
运行结果:
[{b 16} {a 18} {c 21} {e 23} {d 35}]
b 16
a 18
c 21
e 23
d 35