【问题标题】:how to get the sum of duplicate values in a list in dart?如何在飞镖列表中获取重复值的总和?
【发布时间】:2021-02-05 11:43:18
【问题描述】:

我想获取重复值的总和并将它们放在另一个列表中.. 有可能吗?

List list = [1, 1 , 2, 3,2];
List newList = [2,4,3];

【问题讨论】:

  • 确保使用来自collection库的groupBy顶级函数
  • print(groupBy([1,1,2,3,2], (e) => e).values.map((e) => e.reduce((sum, e) => sum + e)));

标签: arrays list sorting flutter dart


【解决方案1】:

当然,这是可能的。您可以定义一个临时列表以防止列表中出现重复项。试试这个:

List list = [1, 1, 2, 3, 2];
List tempList = [];
List newList = [2, 4, 3];

for (var item in list) {
  if (!tempList.contains(item)) {
    newList.add(list.where((e) => e == item).length * item);
    tempList.add(item);
  }
}

【讨论】:

  • 这是groupBy 的用途:print(groupBy([1,1,2,3,2], (e) => e).values.map((e) => e.reduce((sum, e) => sum + e)));
  • 或您的(更快)方式:print(groupBy([1,1,2,3,2], (e) => e).values.map((e) => e[0] * e.length));
  • 你太棒了:)
猜你喜欢
  • 1970-01-01
  • 2020-12-31
  • 2012-08-15
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 2019-07-09
相关资源
最近更新 更多