在Scala中查找列表中元素的索引

61

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

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

如果我要求"little"的索引,那么我需要获得3。

3个回答

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

下次你可以尝试阅读List的scaladoc文档。 ;)


List("Mary", "had", "a", "little", "little").indexOf("little")永远返回3。 - m-bhole

53

如果您想通过谓词进行搜索,请使用 .indexWhere(f)

val ls = List("Mary", "had", "a", "little", "lamb","a")
ls.indexWhere(_.startsWith("l"))

这将返回3,因为“little”是以字母l开头的第一个单词。


40
如果您想要所有包含“a”的索引列表,那么:
val ls = List("Mary", "had", "a", "little", "lamb","a")
scala> ls.zipWithIndex.filter(_._1 == "a").map(_._2)
res13: List[Int] = List(2, 5)

23
有趣!不过我认为这就是collect的用法:ls.zipWithIndex.collect { case ("a",i) => i } - DaoWen
1
有没有办法使用 .collect 和一个变量一起使用?就像 ls.zipWithIndex.collect { case (someVariableIWantToMatch,i) => i } 这样? - Arthur Attout
2
没关系,这是关于稳定标识符的问题。 - Arthur Attout

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接