list 查找列表中元素的索引scala

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17873698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:02:41  来源:igfitidea点击:

Finding the index of an element in a list scala

listscala

提问by yAsH

How do I find the index of an element in a Scala list.

如何在 Scala 列表中找到元素的索引。

val ls = List("Mary", "had", "a", "little", "lamb")

I need to get 3 if I ask for the index of "little"

如果我要求“小”的索引,我需要得到 3

回答by DaoWen

scala> List("Mary", "had", "a", "little", "lamb").indexOf("little")
res0: Int = 3

You might try reading the scaladoc for Listnext time. ;)

下次您可以尝试阅读ListScaladoc。;)

回答by Rok Kralj

If you want to search by a predicate, use .indexWhere(f):

如果要按谓词搜索,请使用.indexWhere(f)

val ls = List("Mary", "had", "a", "little", "lamb","a")
ls.indexWhere(_.size <= 3)

This returns 1, since "had" is the first word with at most 3 letters.

这将返回 1,因为“had”是第一个最多包含 3 个字母的单词。

回答by Jatin

If you want list of all indices containing "a", then:

如果您想要包含“a”的所有索引的列表,则:

val ls = List("Mary", "had", "a", "little", "lamb","a")
scala> ls.zipWithIndex.filter(_._1 == "a").map(_._2)
res13: List[Int] = List(2, 5)