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

Dart如何统计二维列表中每一列的true值数量?

实现代码(易理解的基础写法)

void main() {
  List<List<bool>> a = [
    [true, true, false, false],
    [true, false, false, true]
  ];
  // 处理空列表边界情况,避免后续运行报错
  if (a.isEmpty || a.first.isEmpty) {
    print('result = []');
    return;
  }
  int columnCount = a.first.length;
  List<int> result = [];
  // 遍历每一列
  for (int colIndex = 0; colIndex < columnCount; colIndex++) {
    int trueCount = 0;
    // 统计当前列所有行的true数量
    for (var row in a) {
      if (row[colIndex]) trueCount++;
    }
    result.add(trueCount);
  }
  print('result = $result');
}

运行后直接输出 result = [2, 1, 0, 1],完全匹配预期结果。

简洁的函数式写法

熟悉Dart API的话可以用更短的代码实现:

void main() {
  List<List<bool>> a = [
    [true, true, false, false],
    [true, false, false, true]
  ];
  if (a.isEmpty || a.first.isEmpty) {
    print('result = []');
    return;
  }
  final result = List.generate(
    a.first.length,
    (colIndex) => a.where((row) => row[colIndex]).length
  );
  print('result = $result');
}
  • 用List.generate直接根据列数生成结果数组
  • 用where筛选出当前列值为true的行,取长度直接得到统计值

内容的提问来源于stack exchange,提问作者Theppasin Kongsakda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 03:24:03