迭代 Julia 中数组的每个索引 – eachindex() 方法
eachindex()
是 julia 中的一个内置函数,用于创建一个可迭代对象,用于访问指定数组的每个索引。
Syntax:
eachindex(A…)
Parameters:
- A: Specified array.
Returns: It returns an iterable object for visiting each index of the specified array.
示例 1:
# Julia program to illustrate
# the use of Array eachindex() method
# Accessing each index of 1D array
A = [1, 2, 3, 4];
# linear indexing
for i in eachindex(A)
println(i)
end
# Accessing each index of 2D array
B = [2 4; 6 8];
# linear indexing
for i in eachindex(B)
println(i)
end
# Accessing each index of 3D array
C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3);
# linear indexing
for i in eachindex(C)
println(i)
end
输出:
示例 2:
# Julia program to illustrate
# the use of Array eachindex() method
# Accessing each index of 1D array
A = [1, 2, 3, 4];
# Cartesian indexing
for i in eachindex(view(A, 1:2, 1:1))
println(i)
end
# Accessing each index of 2D array
B = [2 4; 6 8];
# Cartesian indexing
for i in eachindex(view(B, :, 1))
println(i)
end
# Accessing each index of 3D array
C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3);
# Cartesian indexing
for i in eachindex(view(C, :, :, 1))
println(i)
end
输出: