Alec
Alec

Reputation: 4482

Function like `enumerate` for arrays with custom indices?

For an array with a non-one based index like:

using OffsetArrays
a = OffsetArray( [1,2,3], -1)

Is there a simple way to get a tuple of (index,value), similar to enumerate?

Enumerating still counts the elements... collect(enumerate(a)) returns:

3-element Array{Tuple{Int64,Int64},1}:
 (1, 1)
 (2, 2)
 (3, 3)

I'm looking for:

 (0, 1)
 (1, 2)
 (2, 3)

Upvotes: 2

Views: 183

Answers (2)

DNF
DNF

Reputation: 12664

The canonical solution is to use pairs:

julia> a = OffsetArray( [1,2,3], -1);

julia> for (i, x) in pairs(a)
       println("a[", i, "]: ", x)
       end
a[0]: 1
a[1]: 2
a[2]: 3

julia> b = [1,2,3];

julia> for (i, x) in pairs(b)
       println("b[", i, "]: ", x)
       end
b[1]: 1
b[2]: 2
b[3]: 3

It works for other types of collections too:

julia> d = Dict(:a => 1, :b => 2, :c => 3);

julia> for (i, x) in pairs(d)
       println("d[:", i, "]: ", x)
       end
d[:a]: 1
d[:b]: 2
d[:c]: 3

You can find a lot of other interesting iterators by reading the documentation of Base.Iterators.

Upvotes: 3

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42264

Try eachindex(a) to get the indexes, see the example below:

julia> tuple.(eachindex(a),a)
3-element OffsetArray(::Array{Tuple{Int64,Int64},1}, 0:2) with eltype Tuple{Int64,Int64} with indices 0:2:
 (0, 1)
 (1, 2)
 (2, 3)

Upvotes: 3

Related Questions