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
相关产品推荐
相关产品推荐

