我有以下列表作为输入:
val lisinputt=("banana 10",
"apple 20",
"apple 30",
"banana 10",
"berry 10")
我想计算每个元素的出现次数,而不是与每个元素相关的和值,因此想要的输出将是:
val listoutput=("banana 2 20",
"apple 2 50",
"berry 1 10")
请知道如何实现这一目标
答案 0 :(得分:1)
您可以执行以下操作
val lisinputt=("banana 10",
"apple 20",
"apple 30",
"banana 10",
"berry 10")
lisinputt.productIterator.toList
.map(x => {val splitted = x.toString.split("\\s+"); (splitted(0), 1, splitted(1))})
.groupBy(_._1)
.mapValues(x => (x.map(_._2.toInt).sum, x.map(_._3.toInt).sum))
.map(x => Array(x._1, x._2._1, x._2._2).mkString(" "))
.foreach(println)
应该给你
banana 2 20
apple 2 50
berry 1 10
答案 1 :(得分:0)
你可以期待像这样的输出
val listInput=("banana 10",
"apple 20",
"apple 30",
"banana 10",
"berry 10")
val result = listInput.productIterator.toList.map(_.toString.split("\\s+")).groupBy(e=> e.apply(0)).collect{
case e=> (e._1, e._2.size, e._2.map(_.apply(1).toInt).sum)
}
//result: scala.collection.immutable.Iterable[(String, Int, Int)] = List((banana,2,20), (apple,2,50), (berry,1,10))