在 Dart 中从一个列表到另一个列表获取累积 sum/running 总计的更好方法
Better way of getting cumulative sum/running totals from one list to another list in Dart
这是我想做的,比我现在做的更好。
销售员正在清点他的销售额。每天输入他的数据并给我们一个这样的列表:
List<int> weekOneDaily = [3, 4, 2, 7, 13, 34, 22];
我想根据上面的列表创建一个 运行 总列表,这样每一天都会作为自己的条目添加到下一个,如下所示:
List<int> cumulativeDaily = [3, 7, 9, 16, 29, 63, 85];
我目前正在成功地这样做:
List<int> dailySales = [2, 9, 4, 16, 13, 23, 18];
List<int> cumulativeSales =[];
/// Create cumulative list totals
void getCumulative(List<int> list) {
cumulativeSales.add(list.first);
for (var index in list) {
(index == list.first)
? cumulativeSales.add(index)
: cumulativeSales.add(cumulativeSales.last += index);
}
cumulativeSales.removeLast();
print('CUMULATIVE: $cumulativeSales');
}
getCumulative(dailySales);
这有点奇怪,因为它给出了两个相同的最后一个元素,所以我需要删除最后一个元素并需要预渲染第一个元素才能工作。
谁能告诉我一个更简单、更简洁、更简单的解决方案?
请注意我不想这样做video
我会正确地做这样的事情:
/// Create cumulative list totals
List<int> getCumulative(List<int> list) => list.fold(
[], (sums, element) => sums..add(element + (sums.isEmpty ? 0 : sums.last)));
void main() {
print(getCumulative([2, 9, 4, 16, 13, 23, 18])); // [2, 11, 15, 31, 44, 67, 85]
}
或者这个更具可读性:
/// Create cumulative list totals
List<int> getCumulative(List<int> list) {
var sum = 0;
return [for (final value in list) sum += value];
}
void main() {
print(getCumulative([2, 9, 4, 16, 13, 23, 18])); // [2, 11, 15, 31, 44, 67, 85]
}
这是我想做的,比我现在做的更好。
销售员正在清点他的销售额。每天输入他的数据并给我们一个这样的列表:
List<int> weekOneDaily = [3, 4, 2, 7, 13, 34, 22];
我想根据上面的列表创建一个 运行 总列表,这样每一天都会作为自己的条目添加到下一个,如下所示:
List<int> cumulativeDaily = [3, 7, 9, 16, 29, 63, 85];
我目前正在成功地这样做:
List<int> dailySales = [2, 9, 4, 16, 13, 23, 18];
List<int> cumulativeSales =[];
/// Create cumulative list totals
void getCumulative(List<int> list) {
cumulativeSales.add(list.first);
for (var index in list) {
(index == list.first)
? cumulativeSales.add(index)
: cumulativeSales.add(cumulativeSales.last += index);
}
cumulativeSales.removeLast();
print('CUMULATIVE: $cumulativeSales');
}
getCumulative(dailySales);
这有点奇怪,因为它给出了两个相同的最后一个元素,所以我需要删除最后一个元素并需要预渲染第一个元素才能工作。
谁能告诉我一个更简单、更简洁、更简单的解决方案?
请注意我不想这样做video
我会正确地做这样的事情:
/// Create cumulative list totals
List<int> getCumulative(List<int> list) => list.fold(
[], (sums, element) => sums..add(element + (sums.isEmpty ? 0 : sums.last)));
void main() {
print(getCumulative([2, 9, 4, 16, 13, 23, 18])); // [2, 11, 15, 31, 44, 67, 85]
}
或者这个更具可读性:
/// Create cumulative list totals
List<int> getCumulative(List<int> list) {
var sum = 0;
return [for (final value in list) sum += value];
}
void main() {
print(getCumulative([2, 9, 4, 16, 13, 23, 18])); // [2, 11, 15, 31, 44, 67, 85]
}