如何在 Scala 中将 List[(Char,Int)] 求和到 Map[Char,Int] 中?
How to sum a List[(Char,Int)] into a Map[Char,Int] in Scala?
我有配对列表:
List(('a',3),('b',3),('a',1))
我想通过按 _1 分组并求和 _2 来转换它。结果应该像
Map('a'->4, 'b' -> 3)
我对 Scala 很陌生,所以请多关照:)
list.groupBy(_._1).mapValues(_.map(_._2).sum)
可以写成
list.groupBy(_._1).mapValues { tuples =>
val ints = tuples.map { case (c, i) => i }
ints.sum
}
更直接的版本。我们折叠列表,使用 Map 作为累加器。 withDefaultValue
意味着我们不必测试地图中是否已经有条目。
val xs = List(('a',3),('b',3),('a',1))
xs.foldLeft(Map[Char, Int]() withDefaultValue 0)
{case (m, (c, i)) => m updated (c,m(c)+i)}
//> res0: scala.collection.immutable.Map[Char,Int] = Map(a -> 4, b -> 3)
我有配对列表:
List(('a',3),('b',3),('a',1))
我想通过按 _1 分组并求和 _2 来转换它。结果应该像
Map('a'->4, 'b' -> 3)
我对 Scala 很陌生,所以请多关照:)
list.groupBy(_._1).mapValues(_.map(_._2).sum)
可以写成
list.groupBy(_._1).mapValues { tuples =>
val ints = tuples.map { case (c, i) => i }
ints.sum
}
更直接的版本。我们折叠列表,使用 Map 作为累加器。 withDefaultValue
意味着我们不必测试地图中是否已经有条目。
val xs = List(('a',3),('b',3),('a',1))
xs.foldLeft(Map[Char, Int]() withDefaultValue 0)
{case (m, (c, i)) => m updated (c,m(c)+i)}
//> res0: scala.collection.immutable.Map[Char,Int] = Map(a -> 4, b -> 3)