使用Scala中的索引进行高效迭代 [英] Efficient iteration with index in Scala

查看:133
本文介绍了使用Scala中的索引进行高效迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Scala没有旧的Java样式用于带索引的循环,

Since Scala does not have old Java style for loops with index,

// does not work
val xs = Array("first", "second", "third")
for (i=0; i<xs.length; i++) {
  println("String #" + i + " is " + xs(i))
}

我们如何有效地迭代,而不使用 var

How can we iterate efficiently, and without using var's?

你可以这样做

val xs = Array("first", "second", "third")
val indexed = xs zipWithIndex
for (x <- indexed) println("String #" + x._2 + " is " + x._1)

但是列表遍历了两次 - 效率不高。

but the list is traversed twice - not very efficient.

推荐答案

比遍历两次要糟糕得多,它创建了一对中间数组。
您可以使用查看。当您执行 collection.view 时,您可以将后续调用视为在迭代期间懒惰地执行。如果你想回到一个完全实现的完全集合,你最后会调用 force 。这将是无用的和昂贵的。所以将代码更改为

Much worse than traversing twice, it creates an intermediary array of pairs. You can use view. When you do collection.view, you can think of subsequent calls as acting lazily, during the iteration. If you want to get back a proper fully realized collection, you call force at the end. Here that would be useless and costly. So change your code to

for((x,i) <- xs.view.zipWithIndex) println("String #" + i + " is " + x)

这篇关于使用Scala中的索引进行高效迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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