我有一个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。
有谁知道比较两个列表并获得此结果的方法?
我建议将事件列表转换为地图,然后.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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句