我是scala的新手。我有String
,Double
对的列表:
List((Db,0.1574), (C,1.003), (Db,15.4756), (D,0.003), (Bb,1.4278), (D,13.0001))
我想sum
具有公共字符串值的双精度值,并因此创建一个新的对列表:
List((Db, 15.633), (C, 1.003), (D, 13.0031), (Bb, 1.4278)
有关如何执行此操作的任何建议都将有很大帮助。谢谢
答案 0 :(得分:2)
使用groupBy
是一个不错的起点:
list
.groupBy(_._1)
.mapValues(_.map(_._2).sum)
.toList
您也可以使用foldLeft
对值求和,但可能不太清楚。
答案 1 :(得分:0)
检查
scala> val a = List(("Db",0.1574), ("C",1.003), ("Db",15.4756), ("D",0.003), ("Bb",1.4278), ("D",13.0001))
a: List[(String, Double)] = List((Db,0.1574), (C,1.003), (Db,15.4756), (D,0.003), (Bb,1.4278), (D,13.0001))
scala> a.groupBy( x=> x._1).map(x=> (x._1,x._2.map(a=>a._2).sum))
res11: scala.collection.immutable.Map[String,Double] = Map(D -> 13.0031, Db -> 15.633000000000001, C -> 1.003, Bb -> 1.4278)
scala>
scala> a.groupBy( x=> x._1).map(x=> (x._1,x._2.map(a=>a._2).sum)).toList
res12: List[(String, Double)] = List((D,13.0031), (Db,15.633000000000001), (C,1.003), (Bb,1.4278))
scala>