如何映射在Scala中的数组时,你得到的元素索引? [英] How to get the element index when mapping an array in Scala?

查看:320
本文介绍了如何映射在Scala中的数组时,你得到的元素索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个简单的映射例如:

Let's consider a simple mapping example:


  val a = Array("One", "Two", "Three")
  val b = a.map(s => myFn(s))

我需要的是使用没有 myFn(S:字符串):字符串在这里,但 myFn(S:字符串,N:智力) :字符串,其中 N 将指数取值。在这种特殊情况下myFn所期望的第二个参数为0对于s ==一,1对于s ==二和2对于s ==三公。我怎样才能做到这一点?

What I need is to use not myFn(s: String): String here, but myFn(s: String, n: Int): String, where n would be the index of s in a. In this particular case myFn would expect the second argument to be 0 for s == "One", 1 for s == "Two" and 2 for s == "Three". How can I achieve this?

推荐答案

要看是否要方便或速度。

Depends whether you want convenience or speed.

慢速:

a.zipWithIndex.map{ case (s,i) => myFn(s,i) }

更快:

for (i <- a.indices) yield myFn(a(i),i)

{ var i = -1; a.map{ s => i += 1; myFn(s,i) } }

可能最快的:

Array.tabulate(a.length){ i => myFn(a(i),i) }

如果没有,这肯定是:

val b = new Array[Whatever](a.length)
var i = 0
while (i < a.length) {
  b(i) = myFn(a(i),i)
  i += 1
}

(在Scala 2.10.1与Java 1.6u37,如果可能最快的声明采取1X时间为小事字符串操作(长字符串截取几个字符),那么慢需要2倍更长的时间,更快每个1.3倍更长的时间,而肯定只需要0.5倍的时间。)

这篇关于如何映射在Scala中的数组时,你得到的元素索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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