对于具有非基于一的索引的数组,例如:
using OffsetArrays
a = OffsetArray( [1,2,3], -1)
有没有一种简单的方法来获得一个(index,value)
元组,类似于enumerate
?
枚举仍然计算元素...collect(enumerate(a))
回报:
3-element Array{Tuple{Int64,Int64},1}:
(1, 1)
(2, 2)
(3, 3)
我正在寻找:
(0, 1)
(1, 2)
(2, 3)
规范的解决方案是使用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
它也适用于其他类型的集合:
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
您可以通过阅读文档找到许多其他有趣的迭代器Base.Iterators
.
尝试eachindex(a)
获取索引,请参阅以下示例:
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)