Find Indexes *Where*

前端 未结 1 1200
旧巷少年郎
旧巷少年郎 2020-12-19 05:04

There\'s a indexWhere function in Vector that finds the index of a match.

def indexWhere(p: (A) ⇒ Boolean, from: Int): Int
> Fin         


        
相关标签:
1条回答
  • 2020-12-19 05:43

    zipWithIndex, filter, and map are built-ins that can be combined to get all the indices of some predicate.

    Get the indices of the even values in the list.

    scala> List(1,2,3,4,5,6,7,8,9,10).zipWithIndex.filter(_._1 % 2 == 0).map(_._2)
    res0: List[Int] = List(1, 3, 5, 7, 9)
    

    You can also use collect as @0__ notes.

    scala> List(1,2,3,4,5,6,7,8,9,10).zipWithIndex.collect{ case(a,b) if a % 2 == 0 => b}
    res1: List[Int] = List(1, 3, 5, 7, 9)
    
    0 讨论(0)
提交回复
热议问题