如何对元组列表求和 [英] How to sum a list of tuples

查看:38
本文介绍了如何对元组列表求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下元组列表...

Given the following list of tuples...

val list = List((1, 2), (1, 2), (1, 2))

...我如何对所有值求和并获得这样的单个元组?

... how do I sum all the values and obtain a single tuple like this?

(3, 6)

推荐答案

使用 foldLeft 方法.请查看 scaladoc 了解更多信息.

Using the foldLeft method. Please look at the scaladoc for more information.

scala> val list = List((1, 2), (1, 2), (1, 2))
list: List[(Int, Int)] = List((1,2), (1,2), (1,2))

scala> list.foldLeft((0, 0)) { case ((accA, accB), (a, b)) => (accA + a, accB + b) }
res0: (Int, Int) = (3,6)

使用解压.不如上述解决方案有效.也许更具可读性.

Using unzip. Not as efficient as the above solution. Perhaps more readable.

scala> list.unzip match { case (l1, l2) => (l1.sum, l2.sum) }
res1: (Int, Int) = (3,6) 

这篇关于如何对元组列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆