2

我是 Scala 的新手。

如果我有以下情况List

val ls = List("a", "a", "a", "b", "b", "c")

如何Map为列表中的每个元素创建一个包含多个外观的列表?

例如Map上面的列表应该是:

Map("a" -> 3, "b" -> 2, "c" -> 1)
4

3 回答 3

5
list.foldLeft(Map[String, Int]() withDefaultValue 0) { (m, x) => m + (x -> (m(x) + 1)) }

片段在行动:

scala> val list = List("a", "a", "b", "c", "c", "a")
list: List[String] = List(a, a, b, c, c, a)

scala> list.foldLeft(Map[String, Int]() withDefaultValue 0) { (m, x) => m + (x -> (1 + m(x))) }
res1: scala.collection.immutable.Map[String,Int] = Map(a -> 3, b -> 1, c -> 2)

(直接基于Scala 中 List[List[T]] 中每个元素的 Count 出现次数

于 2013-09-13T20:08:32.640 回答
2

不如 Erik 的foldLeft解决方案高效:

val ls = List("a", "a", "a", "b", "b", "c")
ls.groupBy(identity).mapValues(_.size)
res0: scala.collection.immutable.Map[String,Int] = Map(a -> 3, c -> 1, b -> 2)
于 2013-09-13T20:09:39.783 回答
2

斯卡拉兹

xs foldMap (x => Map(x -> 1))
于 2013-09-13T20:36:40.607 回答