如何在Scala列表中找到元素的索引。
val ls = List("Mary", "had", "a", "little", "lamb")
如果我要求"little"的索引,那么我需要获得3。
scala> List("Mary", "had", "a", "little", "lamb").indexOf("little")
res0: Int = 3
下次你可以尝试阅读List的scaladoc文档。 ;)
如果您想通过谓词进行搜索,请使用 .indexWhere(f)
:
val ls = List("Mary", "had", "a", "little", "lamb","a")
ls.indexWhere(_.startsWith("l"))
这将返回3,因为“little”是以字母l开头的第一个单词。
val ls = List("Mary", "had", "a", "little", "lamb","a")
scala> ls.zipWithIndex.filter(_._1 == "a").map(_._2)
res13: List[Int] = List(2, 5)
collect
的用法:ls.zipWithIndex.collect { case ("a",i) => i }
- DaoWen.collect
和一个变量一起使用?就像 ls.zipWithIndex.collect { case (someVariableIWantToMatch,i) => i }
这样? - Arthur Attout