千家信息网

Golang怎么将Map的键值对调

发表于:2024-10-23 作者:千家信息网编辑
千家信息网最后更新 2024年10月23日,这篇文章主要介绍"Golang怎么将Map的键值对调"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"Golang怎么将Map的键值对调"文章能帮助大家解决问题。
千家信息网最后更新 2024年10月23日Golang怎么将Map的键值对调

这篇文章主要介绍"Golang怎么将Map的键值对调"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"Golang怎么将Map的键值对调"文章能帮助大家解决问题。

一、Map是什么?

map是一堆键值对的未排序集合,类似Python中字典的概念,它的格式为map[keyType]valueType,是一个key-value的hash结构。map的读取和设置也类似slice一样,通过key来操作,只是slice的index只能是int类型,而map多了很多类型,可以是int,可以是string及所有完全定义了==与!=操作的类型

二、详细代码

1.对调键值

Map原数据:

moMap := map[string]int{        "张三": 21, "李四": 56, "王五": 23,        "赵六": 45, "周七": 32, "陈八": 21,        "许九": 21, "王十": 16, "吴三": 45,        "郑六": 23, "许七": 43, "李三": 16,    }

具体代码如下(示例):

// 键值对调 // 传入参数:moMap map[string]int// 返回值: map[int][]stringfunc reserveMap(moMap map[string]int) map[int][]string {    // 建立一个 resMap 与 moMap 容量相同    // 由于对调可能存在多个值对应一个Key    // string 需转为 切片[]string    resMap := make(map[int][]string, len(moMap))    // 通过for range 遍历 moMap    // k 即为 Key v 即为 Value    for k, v := range moMap {        // 由于现在对应为 切片[]string        // 使用 append 达到添加多个的效果        resMap[v] = append(resMap[v], k)    }        // 程序结束    return resMap}

2.进行调用

详细代码如下(示例):

package mainimport (    "fmt")func main() {    moMap := map[string]int{        "张三": 21, "李四": 56, "王五": 23,        "赵六": 45, "周七": 32, "陈八": 21,        "许九": 21, "王十": 16, "吴三": 45,        "郑六": 23, "许七": 43, "李三": 16,    }    // 打印对调前    for k, v := range moMap {        fmt.Printf("Key: %v, Value: %v \n", k, v)    }    resMap := reserveMap(moMap)    fmt.Println("reserve:")    // 打印对调后    for k, v := range resMap {        fmt.Printf("Key: %v, Value: %v \n", k, v)    }}// 键值对调// 传入参数:moMap map[string]int// 返回值: map[int][]stringfunc reserveMap(moMap map[string]int) map[int][]string {    // 建立一个 resMap 与 moMap 容量相同    // 由于对调可能存在多个值对应一个Key    // string 需转为 切片[]string    resMap := make(map[int][]string, len(moMap))    // 通过for range 遍历 moMap    // k 即为 Key v 即为 Value    for k, v := range moMap {        // 由于现在对应为 切片[]string        // 使用 append 达到添加多个的效果        resMap[v] = append(resMap[v], k)    }    // 程序结束    return resMap}

总结

键值的简单调换是熟悉Golang Map 数据类型的前奏。

PS:golang 无序的键值对集合map

package mainimport "fmt"func main() {     /*创建集合并初始化 */    countryCapitalMap := make(map[string]string)    /* map插入key - value对,各个国家对应的首都 */    countryCapitalMap [ "France" ] = "巴黎"    countryCapitalMap [ "Italy" ] = "罗马"    countryCapitalMap [ "Japan" ] = "东京"    countryCapitalMap [ "India " ] = "新德里"    /*使用键输出value值 */    for country := range countryCapitalMap {        fmt.Println(country, "首都是", countryCapitalMap [country])    }    /*查看元素在集合中是否存在 */    capital, ok := countryCapitalMap [ "American" ] /*如果确定是真实的,则存在,否则不存在 */    /*fmt.Println(capital) */    /*fmt.Println(ok) */    if (ok) {        fmt.Println("American 的首都是", capital)    } else {        fmt.Println("American 的首都不存在")    }}

关于"Golang怎么将Map的键值对调"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。

0