Kotlin中如何将1104×828的List<List<Int>>拆分为6×12子网格?
解决Kotlin网格分块与归约问题
正确分块实现
你遇到的问题是分块顺序导致维度错位,需要调整分块后维度的顺序来得到目标结构。这里提供两种实现方式:
方式一:使用转置操作
先将大网格按6行一组拆分,再对每组内的行拆分列块,最后通过转置调整维度顺序:
// 自定义转置函数,将List<List<T>>的行和列互换 fun <T> List<List<T>>.transpose(): List<List<T>> { if (isEmpty()) return emptyList() val columnCount = first().size return (0..<columnCount).map { colIndex -> map { row -> row[colIndex] } } } // 假设originalGrid是你的1104×828的List<List<Int>> val originalGrid: List<List<Int>> = // 你的网格数据 // 步骤1:按6行分块,得到184个包含6行的块 val rowGroups = originalGrid.chunked(6) // 步骤2:对每个6行块,先拆分每行成12列的子块,再转置得到69个6×12的子网格 val subGrids: List<List<List<List<Int>>>> = rowGroups.map { group -> group.map { row -> row.chunked(12) }.transpose() }
方式二:直接循环遍历列块索引
如果不想自定义转置函数,也可以通过循环直接提取对应列块:
val originalGrid: List<List<Int>> = // 你的网格数据 val rowGroups = originalGrid.chunked(6) val columnChunkCount = 828 / 12 // 固定为69 val subGrids: List<List<List<List<Int>>>> = rowGroups.map { group -> (0..<columnChunkCount).map { chunkIdx -> group.map { row -> row.chunked(12)[chunkIdx] } } }
两种方式最终得到的subGrids结构都是184×69×6×12,完全符合你的需求。
快速归约得到184×69网格
基于上面的分块结果,直接嵌套map即可完成归约操作。比如以子网格求和为例:
// 归约每个6×12子网格为单个值(这里是求和) val reducedGrid: List<List<Int>> = subGrids.map { rowGroup -> rowGroup.map { subGrid -> subGrid.sumOf { row -> row.sum() } } }
你可以根据实际需求替换归约逻辑(比如求平均值、最大值等)。
内容的提问来源于stack exchange,提问作者Sebastian
相关产品推荐
相关产品推荐

