本文介绍了如何在 Scala 中使用地图并接收索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何内置的 List/Sequence 的行为类似于 map
并提供元素的索引?
Is there any List/Sequence built-in that behaves like map
and provides the element's index as well?
推荐答案
我相信您正在寻找 zipWithIndex?
I believe you're looking for zipWithIndex?
scala> val ls = List("Mary", "had", "a", "little", "lamb")
scala> ls.zipWithIndex.foreach{ case (e, i) => println(i+" "+e) }
0 Mary
1 had
2 a
3 little
4 lamb
来自:http://www.artima.com/forums/flat.jsp?forum=283&thread=243570
你也有类似的变体:
for((e,i) <- List("Mary", "had", "a", "little", "lamb").zipWithIndex) println(i+" "+e)
或:
List("Mary", "had", "a", "little", "lamb").zipWithIndex.foreach( (t) => println(t._2+" "+t._1) )
这篇关于如何在 Scala 中使用地图并接收索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!