如何在Scala中使用map并接收索引? [英] How can I use map and receive an index as well in Scala?

查看:354
本文介绍了如何在Scala中使用map并接收索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ p $ / h2_lin>解决方案

我相信你正在寻找zipWithIndex?

  scala> val ls = List(Mary,had,a,little,lamb)
scala> ls.zipWithIndex.foreach {case(e,i)=> println(i ++ e)}
0 Mary
1有
2 a
3 little
4 lamb

来自: http://www.artima.com/forums/flat.jsp?forum=283&thread=243570



您还有((e,i)< - List(Mary,had,a)的变体如下:

  ,little,lamb)。zipWithIndex)println(i ++ e)

 列表(Mary,had,a,little,lamb)zipWithIndex。 foreach((t)=> println(t._2 ++ t._1))


Is there any List/Sequence built-in that behaves like map and provides the element's index as well?

解决方案

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

From: http://www.artima.com/forums/flat.jsp?forum=283&thread=243570

You also have variations like:

for((e,i) <- List("Mary", "had", "a", "little", "lamb").zipWithIndex) println(i+" "+e)

or:

List("Mary", "had", "a", "little", "lamb").zipWithIndex.foreach( (t) => println(t._2+" "+t._1) )

这篇关于如何在Scala中使用map并接收索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆