Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function like enumerate to get index and value for offset arrays?

If I have an array like this:

using OffsetArrays

a = OffsetArray(collect(1:5),(11:15))

I can iterate through the array with:

for (i,x) in enumerate(a)
    println((i,x))
end

and get:

(1, 1)
(2, 2)
(3, 3)
(4, 4)
(5, 5)

But I want this:

(11, 1)
(12, 2)
(13, 3)
(14, 4)
(15, 5)

Is there a way to get the real index since I am using an offset array?

like image 291
Alec Avatar asked Jan 31 '20 04:01

Alec


People also ask

What is the difference between index and offset in Excel?

While the OFFSET function moves from the starting point by a certain number of rows and/or columns, INDEX finds a cell at the intersection of a particular row and column.

How do I index an array in Swift?

To get the first index of an item in an array in Swift, use the array. firstIndex(where:) method. print(i1!)

What is the need of index in an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.


1 Answers

The function pairs respects the indexing behaviour:

julia> using OffsetArrays

julia> a = OffsetArray(collect(1:5),(11:15))

julia> for (i,x) in pairs(a)
         println((i,x))
       end

(11, 1)
(12, 2)
(13, 3)
(14, 4)
(15, 5)

from the docs:

Base.pairsFunction.

pairs(collection)

Return an iterator over key => value pairs for any collection that maps a set of keys to a set of values. This includes arrays, where the keys are the array indices.

pairs(IndexLinear(), A)
pairs(IndexCartesian(), A)
pairs(IndexStyle(A), A)

An iterator that accesses each element of the array A, returning i => x, where i is the index for the element and x = A[i]. Identical to pairs(A), except that the style of index can be selected. Also similar to enumerate(A), except i will be a valid index for A, while enumerate always counts from 1 regardless of the indices of A.

Specifying IndexLinear() ensures that i will be an integer; specifying IndexCartesian() ensures that i will be a CartesianIndex; specifying IndexStyle(A) chooses whichever has been defined as the native indexing style for array A.

Mutation of the bounds of the underlying array will invalidate this iterator.

like image 108
longemen3000 Avatar answered Oct 31 '22 11:10

longemen3000