我的列表格式如下:
List(List(21, Georgetown, Male),List(29, Medford, Male),List(18, Manchester, Male),List(27, Georgetown, Female))
我需要计算每个唯一城镇名称的出现次数,然后返回城镇名称及其计算次数。但我只想回到一个发生率最高的城镇。因此,如果我将该函数应用于上面的列表,我会得到
(Georgetown, 2)
我来自Java,所以我知道如何以更长的方式完成这个过程,但我想利用Scala的一些内置方法。
答案 0 :(得分:3)
scala> val towns = List(
| List(21, "Georgetown", "Male"),
| List(29, "Medford", "Male"),
| List(18, "Manchester", "Male"),
| List(27, "Georgetown", "Female"))
towns: List[List[Any]] = ...
scala> towns.map({ case List(a, b, c) => (b, c) }).groupBy(_._1).mapValues(_.length).maxBy(_._2)
res0: (Any, Int) = (Georgetown,2)
答案 1 :(得分:2)
这是一个非常奇怪的结构,但实现它的方法是:
val items : List[List[Any]] = List(
List(List(21, "Georgetown", "Male")),
List(List(29, "Medford", "Male")),
List(List(18, "Manchester", "Male")),
List(List(27, "Georgetown", "Female"))).map(_.flatten)
val results = items.foldLeft(Map[String,Int]()) {
(acc,item) =>
val key = item(1).asInstanceOf[String]
val count = acc.getOrElse(key, 0 )
acc + (key -> (count + 1))
}
println(results)
产生:
Map(Georgetown -> 2, Medford -> 1, Manchester -> 1)