scala 如何对元组列表求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30154736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:08:29  来源:igfitidea点击:

How to sum a list of tuples

scalasumtuples

提问by j3d

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)

回答by Lomig Mégard

Using the foldLeftmethod. Please look at the scaladocfor more information.

使用foldLeft方法。请查看scaladoc以获取更多信息。

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.

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

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

回答by rightfold

Very easy: (list.map(_._1).sum, list.map(_._2).sum).

很简单:(list.map(_._1).sum, list.map(_._2).sum)

回答by Valy Dia

You can solve this using Monoid.combineAllfrom the catslibrary:

您可以使用解决这个Monoid.combineAllcats库:

import cats.instances.int._ // For monoid instances for `Int`
import cats.instances.tuple._  // for Monoid instance for `Tuple2`
import cats.Monoid.combineAll

  def main(args: Array[String]): Unit = {

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

    val res = combineAll(list)

    println(res)
    // Displays
    // (3, 6)
  }

You can see more about this in the cats documentationor Scala with Cats.

您可以在cat 文档Scala with Cats 中了解更多相关信息。

回答by Mario Galic

Scalaz solution (suggestied by Travis and for some reason a deleted answer):

Scalaz 解决方案(由 Travis 建议,出于某种原因删除了答案):

import scalaz._
import Scalaz._

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

which outputs

哪个输出

res0: (Int, Int) = (3,6)

回答by Magesh Somasundaram

answering to this question while trying to understand aggregate function in spark

在尝试理解 spark 中的聚合函数时回答这个问题

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

   scala>  list.aggregate((0,0))((x,y)=>((y._1+x._1),(x._2+y._2)),(x,y)=>(x._1+y._2,y._2+x._2))
res89: (Int, Int) = (3,6)

Here is the link to the SO QA that helped to understand and answer this [Explain the aggregate functionality in Spark

这是 SO QA 的链接,有助于理解和回答这个问题 [解释 Spark 中的聚合功能