Scala 查找索引*在哪里*
Scala 查找索引*在哪里*,scala,Scala,Vector中有一个indexWhere函数,用于查找匹配的索引 def indexWhere(p: (A) ⇒ Boolean, from: Int): Int > Finds index of the first element satisfying some predicate after or > at some start index. 我编写这个函数是为了查找发生这种匹配的所有索引 def getAllIndexesWhere[A,B](as: List[A])
Vector
中有一个indexWhere
函数,用于查找匹配的索引
def indexWhere(p: (A) ⇒ Boolean, from: Int): Int
> Finds index of the first element satisfying some predicate after or
> at some start index.
我编写这个函数是为了查找发生这种匹配的所有索引
def getAllIndexesWhere[A,B](as: List[A])(f: (B => Boolean))(g: A => B): Vector[B] = {
def go(y: List[A], acc: List[Option[B]]): Vector[B] = as match {
case x :: xs => val result = if (f(g(x))) Some(g(x)) else None
go(xs, acc :+ result)
case Nil => acc.flatten.toVector
}
go(as, Nil)
}
但是,是否已经存在集合的内置函数?
zipWithIndex
、filter
、以及map
都是内置函数,可以组合起来获得某些谓词的所有索引
获取列表中偶数值的索引
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)
您也可以使用收集
作为@0_uuu注释
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)
您可以使用
collect
:collect{case(elem,idx)if pred(elem)=>idx}
非常好,Brian,谢谢。你能举个例子吗?collect
?(1到10)。zipWithIndex.collect{case(elem,idx)如果elem%2==0=>idx}
使用索引压缩和重新映射会带来额外的开销吗?我想vector一定已经有了索引,这是zip允许您访问的,还是它构造了一个新的集合?