在Scala中映射数组时如何获取元素索引? [英] How to get the element index when mapping an array in Scala?
问题描述
让我们考虑一个简单的映射示例:
Let's consider a simple mapping example:
val a = Array("One", "Two", "Three")
val b = a.map(s => myFn(s))
我需要在这里使用的不是 myFn(s: String): String
,而是 myFn(s: String, n: Int): String
,其中 n
将是 a
中 s
的索引.在这种特殊情况下,myFn 期望第二个参数对于 s == "One" 为 0,对于 s == "Two" 为 1,对于 s == "Three" 为 2.我怎样才能做到这一点?
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
}
(在带有 Java 1.6u37 的 Scala 2.10.1 中,如果声明可能最快"需要 1 倍的时间来执行一个简单的字符串操作(将长字符串截断为几个字符),那么慢"需要长 2 倍,更快"每个需要 1.3 倍的时间,而肯定"只需要 0.5 倍的时间.)
这篇关于在Scala中映射数组时如何获取元素索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!