替代 Julia 中的嵌套 for 循环

Alternative to nested for-loop in Julia

给定任意整数 a 和 b,我想在 Z_a^b \times Z_a^b 内创建所有不同对的列表。比如取a=3和b=2,我想有一个数组

[[[0,0],[0,0]],[[0,0],[0,1]],[[0,0],[0,2]],...,[[2,2],[2,1]],[[2,2],[2,2]]] 

我想在 Julia 中执行此操作。但是,我不知道如何轻松地为 b 的任意值执行此操作(即使对于固定的 b,我能想到的唯一方法是嵌套 for 循环)。有没有快速实现的方法?

这是你想要的吗?

julia> Z(a, b) = Iterators.product([0:a-1 for _ in 1:b]...)
Z (generic function with 1 method)

julia> collect(Iterators.product(Z(3,2), Z(3,2))) |> vec
81-element Vector{Tuple{Tuple{Int64, Int64}, Tuple{Int64, Int64}}}:
 ((0, 0), (0, 0))
 ((1, 0), (0, 0))
 ((2, 0), (0, 0))
 ((0, 1), (0, 0))
 ((1, 1), (0, 0))
 ((2, 1), (0, 0))
 ((0, 2), (0, 0))
 ((1, 2), (0, 0))
 ((2, 2), (0, 0))
 ((0, 0), (1, 0))
 ⋮
 ((0, 0), (2, 2))
 ((1, 0), (2, 2))
 ((2, 0), (2, 2))
 ((0, 1), (2, 2))
 ((1, 1), (2, 2))
 ((2, 1), (2, 2))
 ((0, 2), (2, 2))
 ((1, 2), (2, 2))
 ((2, 2), (2, 2))

julia> collect(Iterators.product(Z(4,3), Z(4,3))) |> vec
4096-element Vector{Tuple{Tuple{Int64, Int64, Int64}, Tuple{Int64, Int64, Int64}}}:
 ((0, 0, 0), (0, 0, 0))
 ((1, 0, 0), (0, 0, 0))
 ((2, 0, 0), (0, 0, 0))
 ((3, 0, 0), (0, 0, 0))
 ((0, 1, 0), (0, 0, 0))
 ((1, 1, 0), (0, 0, 0))
 ((2, 1, 0), (0, 0, 0))
 ((3, 1, 0), (0, 0, 0))
 ((0, 2, 0), (0, 0, 0))
 ((1, 2, 0), (0, 0, 0))
 ⋮
 ((3, 1, 3), (3, 3, 3))
 ((0, 2, 3), (3, 3, 3))
 ((1, 2, 3), (3, 3, 3))
 ((2, 2, 3), (3, 3, 3))
 ((3, 2, 3), (3, 3, 3))
 ((0, 3, 3), (3, 3, 3))
 ((1, 3, 3), (3, 3, 3))
 ((2, 3, 3), (3, 3, 3))
 ((3, 3, 3), (3, 3, 3))

请注意,我 collect 它是为了让结果可见。通常,由于结果集可能非常大,最好使用惰性 Iterators.product 并对其进行迭代。