Is there a convenient/shorthand way to iterate through a for loop on an array, getting both value and index?
Basic options:
i = 1
for file in ["foo.csv", "bar.csv"]
...
i += 1
end
files = ["foo.csv", "bar.csv"]
for i in 1:length(files)
files[i]
end
Edit: As Matt B points out, pairs
is simple and index-safe (if using an OffsetArray
, named tuple, dictionary etc.):
for (i, file) in pairs(["foo.csv", "bar.csv"])
...
end
One option is enumerate
:
for (i, file) in enumerate(["foo.csv", "bar.csv"])
...
end
but note that enumerate doesn't necessarily provide valid indices, since it's effectively zip(x, countfrom(1))
and would break for OffsetArray
s.
Another that's index-safe, but requires files
to be a variable:
files = ["foo.csv", "bar.csv"]
for (i, file) in zip(eachindex(files), files)
...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With