【问题标题】:can i sum of values that has the same key in dictionary我可以对字典中具有相同键的值求和吗
【发布时间】:2021-10-07 06:38:49
【问题描述】:

我有一本这样的字典:

let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]

我想要具有相同键的值的总和。

输出应如下所示:

["foo":7, "bar":8, "bat":12]

【问题讨论】:

  • 字典键不需要唯一吗?
  • @esqew KeyValuePairs 可以有重复项
  • 当您的意思是“KeyValuePairs”时,不要说“字典”。前者需要唯一的键,而后者不需要。

标签: ios swift dictionary


【解决方案1】:

KeyValuePairs 回复 reduce 所以你可以这样做

let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]

let result : [String:Int] = dic.reduce(into: [:]) { (current, new) in
    current[new.key] = new.value + (current[new.key] ?? 0)
}

【讨论】:

  • @Caleb 是的,我做到了。
  • 是的,我运行了代码,它正在按我的意愿工作
  • @JanmejayYadav 你可以使用基于字典键的下标默认值let result = dic.reduce(into: [:]) { $0[$1.key, default: 0] += $1.value }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
相关资源
最近更新 更多