2016-04-29 74 views
0

我有一個List[(String, Int)]List[String]在斯卡拉比較兩個名單

第一個包含一個字的出現次數的字符串,例如:

「這是像其他樣本串的樣本串」

列表List[(String, Int)]是:

List(("This", 1), ("is", 1), ("a", 1), ("sample", 2), ("string", 2), ...) 

第二列表包含多個字符串,讓我們說,它包含:

List("one", "two", "string", "is") 

比較兩個字符串我希望得到以下幾點:

Result = 3 

因爲第二個列表包含「字符串」和「是」,並在列表字符串包含兩個「串」和一個「是」。所以2 + 1 = 3。

有誰知道一種方法來比較兩個列表並得到這個結果?

回答

2

我建議在出現列表轉換成地圖,然後運行.map(..).sum在第二列表:

scala> val occurrences = List(("This", 1), ("is", 1), ("a", 1), ("sample", 2), ("string", 2)).toMap 
occurrences: scala.collection.immutable.Map[String,Int] = Map(is -> 1, This -> 1, a -> 1, string -> 2, sample -> 2) 

scala> val input = List("one", "two", "string", "is") 
input: List[String] = List(one, two, string, is) 

scala> val answer = input.map(occurrences.getOrElse(_, 0)).sum 
answer: Int = 3 
+0

工作很棒。謝謝。 – undisp

2

您可以使用foldLeft:

val l1: List[(String, Int)] = ??? 
val l2: List[String] = ??? 

l1.foldLeft(0)((acc, p) => if(l2.contains(p._1)) acc+p._2 else acc) 

如果您需要優化它,您可以先將l2轉換爲Set,然後該包含應該大部分爲O(1)而不是線性。