查找索引*哪里*

编程入门 行业动态 更新时间:2024-10-26 17:27:50
本文介绍了查找索引*哪里*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Vector 中有一个 indexWhere 函数,用于查找匹配项的索引.

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

def indexWhere(p: (A) ⇒ Boolean, from: Int): Int > Finds index of the first element satisfying some predicate after or > at some start index.

www.scala-lang/api/current/index.html#scala.collection.immutable.Vector

我编写了这个函数来查找发生这种匹配的所有索引.

I wrote this function to find all indexes where such a match occurs.

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) }

但是,是否已经有集合的内置函数?

However, is there already a built-in function of a collection?

推荐答案

zipWithIndex、filter 和 map 是可以组合起来得到某个谓词的所有索引.

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)

您也可以使用 collect 作为 @0__ 笔记.

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)

更多推荐

查找索引*哪里*

本文发布于:2023-10-04 16:15:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467191.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!