Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for-loop to iterate through an array with both value and index

Tags:

julia

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
like image 452
Ian Avatar asked Oct 03 '19 19:10

Ian


1 Answers

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 OffsetArrays.

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
like image 76
Ian Avatar answered Oct 25 '22 23:10

Ian