Reputation: 1255
I'd like the convienience of
for i, line in enumerate(open(sys.argv[1])):
print i, line
when doing the following in Scala
for (line <- Source.fromFile(args(0)).getLines()) {
println(line)
}
Upvotes: 46
Views: 13853
Reputation: 1667
As already answered by others, if you want your index to start from 0, you can use zipWithIndex
:
for ((elem, i) <- collection.zipWithIndex) {
println(i, elem)
}
Because zipWithIndex
creates a copy of the collection if called on the collection itself, you may want to call it to a view
of the colleciton instead: collection.view.zipWithIndex
.
Nonetheless, Python's enumerate
has an optional parameter to set the start value of your index. In scala, you can do:
for ((elem, i) <- collection.zip(Stream from 1) {
println(i, elem)
}
For a longer discussion, read https://alvinalexander.com/scala/how-to-use-zipwithindex-create-for-loop-counters-scala-cookbook.
Upvotes: 11
Reputation: 3932
You can use the zipWithIndex
from Iterable trait:
for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {
println(i, line)
}
Upvotes: 57