Golang将Map的键值对调的实现示例
目录
- 一、Map是什么?
- 二、详细代码
- 1.对调键值
- 2.进行调用
- 总结
- PS: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][]string
func 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 main
import (
    "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][]string
func 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 main
import "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的键值对调的实现示例的文章就介绍到这了,更多相关Golang Map键值对调 内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
 赞 (0)
                        
