是否有一个Scala等效的python枚举?

Abh*_*rma 35 scala enumerate

我喜欢这种方便

for i, line in enumerate(open(sys.argv[1])):
  print i, line
Run Code Online (Sandbox Code Playgroud)

在Scala中执行以下操作时

for (line <- Source.fromFile(args(0)).getLines()) {
  println(line)
}
Run Code Online (Sandbox Code Playgroud)

raf*_*ufo 45

您可以使用zipWithIndexfrom Iterable特征:

for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {
   println(i, line)
}
Run Code Online (Sandbox Code Playgroud)

  • Python也是如此.这是序列索引的标准.方法是`zipWithIndex`,而不是`zipWithLineNumber` (10认同)

sbo*_*oby 9

正如其他人已经回答的那样,如果您希望索引从 0 开始,则可以使用zipWithIndex

for ((elem, i) <- collection.zipWithIndex) {
    println(i, elem)
}
Run Code Online (Sandbox Code Playgroud)

因为zipWithIndex如果在集合本身上调用,则会创建集合的副本,所以您可能希望将其调用到view集合的 a 代替:collection.view.zipWithIndex

尽管如此,Pythonenumerate有一个可选参数来设置索引的起始值。在 Scala 中,您可以执行以下操作:

for ((elem, i) <- collection.zip(Stream from 1) {
    println(i, elem)
}
Run Code Online (Sandbox Code Playgroud)

如需更长时间的讨论,请阅读https://alvinalexander.com/scala/how-to-use-zipwithindex-create-for-loop-counters-scala-cookbook