scala列表计数元素并从其他列表中查找索引

时间:2015-08-27 15:51:51

标签: scala

有没有人对这个好的实现有个好主意:

//Input
val sequenceRef = List("a","b","c","d")        //no doublon
val listToCount = List("b", "c", "b", "a")    //possible doublon

//Output
val listOutput = List(1, 2, 1, 0)

1 - > listToCount中有一个“a”,它位于listRef中的第一个indice 2 - > listToCount中有两个b“,它位于listRef的第二个指示中 3 - > listToCount中有一个“c”,它位于listRef中的第三个指示 0 - > listToCount中没有d

2 个答案:

答案 0 :(得分:3)

val result = sequenceRef.map(x => listToCount.count(_ == x))
println(result)

会给你:

List(1, 2, 1, 0)

答案 1 :(得分:2)

使用中间人Map以避免必须为listToCount的每个元素执行sequenceRef的另一种方式,代价是必须将另一个集合保留在内存中:

scala> val sequenceRef = List("a","b","c","d")
sequenceRef: List[String] = List(a, b, c, d)

scala> val listToCount = List("b", "c", "b", "a")
listToCount: List[String] = List(b, c, b, a)

scala> val keysCount = listToCount.groupBy(identity).mapValues(_.length)
keysCount: scala.collection.immutable.Map[String,Int] = Map(b -> 2, a -> 1, c -> 1)

scala> sequenceRef.map(keysCount.getOrElse(_, 0))
res2: List[Int] = List(1, 2, 1, 0)