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)而不是线性。