2016-11-21 59 views
0

我有一個字頻陣列是這樣的:反向字頻地圖Scala中

[("hello", 1), ("world", 5), ("globle", 1)] 

我不得不reverse它使得我得到的頻率 - 的wordCount地圖像這樣: [(1- ,2),(5,1)]

請注意,由於兩個單詞(「hello」和「globe」)的頻率爲1,因此映射的值爲2。但是,由於只有一個詞的頻率爲5,所以該條目的值爲1。我怎樣才能在scala中做到這一點?

更新:

我碰巧想出解決辦法,以及:

arr.groupBy(_._2).map(x => (x._1,x._2.toList.length)) 
+3

可能[斯卡拉我如何計算列表中出現的次數]的副本(http://stackoverflow.com/questions/11448685/scala-how-can-i-count-the-number-of-occurrences-in-a -list) – Yogesh

+0

你不需要' .toList'因爲'x._2'集合已經有一個'length'方法。 – jwvh

回答

4

您可以第一組由計數,然後就得到各組的大小

val frequencies = List(("hello", 1), ("world", 5), ("globle", 1)) 
val reversed = frequencies.groupBy(_._2).mapValues(_.size).toList 
res0: List[(Int, Int)] = List((5,1), (1,2)) 
+0

謝謝。我碰巧找出了一個替代答案。更新我的原始帖子。謝謝。 –