给定任意整数a和b,我想创建一个包含Z_a^b 乘以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,我能想到的唯一方法就是嵌套循环)。是否有快速实现这一点的方法?
这是你想要的吗?
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
并只迭代它。