Scala是否有类似Python中enumerate的功能?

45

我希望有方便的

for i, line in enumerate(open(sys.argv[1])):
  print i, line

在使用Scala时,执行以下操作:

for (line <- Source.fromFile(args(0)).getLines()) {
  println(line)
}
2个回答

57

您可以使用Iterable特质中的 zipWithIndex 方法:

for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {
   println(i, line)
}

谢谢,但我认为它应该是:for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) - Abhinav Sharma
我不知道Python具体做了什么,但这里的第一行从索引0开始而不是1。 - Jesper
10
Python也是这样做的。这是序列索引的标准方法。该方法为zipWithIndex,而非zipWithLineNumber - rafalotufo

10

就像其他人已经回答的那样,如果你想让你的索引从0开始,你可以使用zipWithIndex:

for ((elem, i) <- collection.zipWithIndex) {
    println(i, elem)
}

由于在集合本身上调用 zipWithIndex 会创建一个集合副本,因此您可能希望将其应用于集合的 viewcollection.view.zipWithIndex

尽管如此,Python 的 enumerate 具有可选参数来设置索引的起始值。在 Scala 中,可以使用以下方式:

for ((elem, i) <- collection.zip(Stream from 1) {
    println(i, elem)
}

想要更深入的讨论,请阅读https://alvinalexander.com/scala/how-to-use-zipwithindex-create-for-loop-counters-scala-cookbook


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接