要将一维 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/lERe 著作权归作者所有。请勿转载和采集!

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