Ale*_*lec 8 arrays indexing julia
如果我有这样的数组:
using OffsetArrays
a = OffsetArray(collect(1:5),(11:15))
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式遍历数组:
for (i,x) in enumerate(a)
println((i,x))
end
Run Code Online (Sandbox Code Playgroud)
并得到:
(1, 1)
(2, 2)
(3, 3)
(4, 4)
(5, 5)
Run Code Online (Sandbox Code Playgroud)
但我想要这个:
(11, 1)
(12, 2)
(13, 3)
(14, 4)
(15, 5)
Run Code Online (Sandbox Code Playgroud)
有没有办法获得真正的索引,因为我使用的是偏移数组?
该函数pairs
尊重索引行为:
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)
Run Code Online (Sandbox Code Playgroud)
Base.pairs
—功能。
pairs(collection)
key => value
为将一组键映射到一组值的任何集合返回对的迭代器。这包括数组,其中键是数组索引。Run Code Online (Sandbox Code Playgroud)pairs(IndexLinear(), A) pairs(IndexCartesian(), A) pairs(IndexStyle(A), A)
访问数组中每个元素的迭代器
A
,返回i => x
, 其中i
是元素的索引 和x = A[i]
。与 相同pairs(A)
,只是可以选择索引的样式。也类似于enumerate(A)
, excepti
将是 的有效索引A
,而enumerate
无论 的索引如何,始终从 1 开始计数A
。指定
IndexLinear()
确保i
将是一个整数;指定IndexCartesian()
确保i
将是一个CartesianIndex
; 指定IndexStyle(A)
选择已定义为 array 的本机索引样式的任何一个A
。底层数组边界的变异将使这个迭代器失效。
归档时间: |
|
查看次数: |
126 次 |
最近记录: |