You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:48:01