要将一维map转换成三维map,需要定义三个维度的key,并将一维map中的值按照这三个key进行分组。

以下是一个示例代码,将一维map中的值按照“年份-月份-日期”三个维度进行分组:

// 定义一维map
oneDimMap := map[string]int{
    "20190101": 100,
    "20190102": 200,
    "20190201": 300,
    "20190202": 400,
}

// 定义三维map
threeDimMap := make(map[string]map[string]map[string]int)

// 遍历一维map,按照年份、月份、日期进行分组
for dateStr, value := range oneDimMap {
    year := dateStr[:4]
    month := dateStr[4:6]
    day := dateStr[6:]

    if _, ok := threeDimMap[year]; !ok {
        threeDimMap[year] = make(map[string]map[string]int)
    }
    if _, ok := threeDimMap[year][month]; !ok {
        threeDimMap[year][month] = make(map[string]int)
    }
    threeDimMap[year][month][day] = value
}

// 输出三维map
fmt.Println(threeDimMap)

输出结果如下:

map[2019:map[01:map[01:100 02:200] 02:map[01:300 02:400]]]

可以看到,输出的三维map已经按照“年份-月份-日期”三个维度进行了分组。

go 如何将一维map 转换成三维map

原文地址: https://www.cveoy.top/t/topic/sOd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录