How to sum a list of tuples
问题 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) 回答1: 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.