如何从固定集生成固定大小的所有不同2D阵列?

问题描述 投票:1回答:1

基本上我想要的是:给定一个m x n数组和一个非空集,以生成包含这些元素的所有不同列表。例如,给定一个2x2数组,并设置{0,1,2},我期待回来:

[[0, 0], [0,0]]

[[0, 0], [0,1]]

[[0, 0], [0,2]]

[[0, 0], [1,0]]

[[0, 0], [1,1]]

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

[[0, 0], [2,0]]

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

[[0, 0], [2,2]]

[[0, 1], [0,0]]

等等。我正在使用Python,但伪代码或类似的东西都可以。我似乎无法弄清楚如何做到这一点。

python
1个回答
1
投票
from itertools import product
x = [0, 1, 2] #define the set you want to work on
b = product(x, repeat=4)
# repeat should be the sum of dimension of the desired output 2+2 = 4 in this case
c = [[i[:2], i[2:]] for i in b]
#outputs [[(0, 0), (0, 0)], [(0, 0), (0, 1)], [(0, 0), (0, 2)], [(0, 0), (1, 0)], ...
© www.soinside.com 2019 - 2024. All rights reserved.