indexing - 具有自定义索引的数组的功能类似于 `enumerate`?

标签 indexing iteration julia

对于具有 non-one based index 的数组喜欢:

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

有没有类似enumerate的简单方法获取(index,value)的元组?

枚举仍然计算元素...collect(enumerate(a)) 返回:

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

我在找:

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

最佳答案

规范的解决方案是使用:

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 的文档,您可以找到许多其他有趣的迭代器。

关于indexing - 具有自定义索引的数组的功能类似于 `enumerate`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62233793/

相关文章:

在 Julia 中保存数据

jQuery has() 没有按预期工作

directory - 如何列出 Julia 目录中的所有文件和目录?

objective-c - iOS 初学者 : UIAlertView Window with 3 Buttons > Check what button was pressed

python - 如何使用 iloc[:, 0] 将第一列设置为索引

algorithm - 简单 : Solve T(n)=T(n-1)+n by Iteration Method

javascript for循环,如果增量值不匹配则嵌套?

Julia 中的稀疏复数矩阵

MySQL 慢双连接

mysql - 同一 Mysql 数据库的两个实例之间的加入顺序不同