Dart中如何将整型数组按指定长度拆分为多个不同长度的分块
你可以通过遍历分块长度列表,配合Dart列表自带的sublist()方法按指定长度截取子列表实现需求,完整代码如下:
void main() { List<int> mainList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; List<int> chukLengths= [2,4,4,4,2]; // 可选校验:先判断分块总长度和原列表长度是否匹配,避免运行时越界 int totalChunkLength = chukLengths.reduce((value, element) => value + element); if (totalChunkLength != mainList.length) { print('分块总长度与原列表长度不匹配'); return; } List<List<int>> result = []; int currentPos = 0; for (int len in chukLengths) { // 截取对应长度的子列表加入结果 result.add(mainList.sublist(currentPos, currentPos + len)); currentPos += len; } print(result); // 输出 [[1, 2], [3, 4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14], [15, 16]] }
如果需要高频使用该能力,可以封装为列表扩展方法,调用更简洁:
// 扩展方法定义 extension CustomSplit<T> on List<T> { List<List<T>> splitBySpecifiedLengths(List<int> chunkLengths) { int total = chunkLengths.reduce((a, b) => a + b); if (total != length) throw ArgumentError('分块总长度和当前列表长度不一致'); int index = 0; return chunkLengths.map((len) { final subList = sublist(index, index + len); index += len; return subList; }).toList(); } } // 调用示例 void main() { List<int> mainList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; List<int> chukLengths= [2,4,4,4,2]; final result = mainList.splitBySpecifiedLengths(chukLengths); print(result); }
内容的提问来源于stack exchange,提问作者Subair K
相关产品推荐
相关产品推荐

