如何在Python中生成0-1矩阵的所有可能组合?
如何生成大小为K×N的0-1矩阵的所有可能组合 例如,如果取K=2和N=2,则得到以下组合如何在Python中生成0-1矩阵的所有可能组合?,python,combinations,Python,Combinations,如何生成大小为K×N的0-1矩阵的所有可能组合 例如,如果取K=2和N=2,则得到以下组合 combination 1 [0, 0; 0, 0]; combination 2 [1, 0; 0, 0]; combination 3 [0, 1; 0, 0]; combination 4 [0, 0; 1, 0]; combination 5 [0, 0; 0, 1]; combination 6 [1, 1; 0, 0]; combination 7 [1, 0; 1,
combination 1
[0, 0;
0, 0];
combination 2
[1, 0;
0, 0];
combination 3
[0, 1;
0, 0];
combination 4
[0, 0;
1, 0];
combination 5
[0, 0;
0, 1];
combination 6
[1, 1;
0, 0];
combination 7
[1, 0;
1, 0];
combination 8
[1, 0;
0, 1];
combination 9
[0, 1;
1, 0];
combination 10
[0, 1;
0, 1];
combination 11
[0, 0;
1, 1];
combination 12
[1, 1;
1, 0];
combination 13
[0, 1;
1, 1];
combination 14
[1, 0;
1, 1];
combination 15
[1, 1;
0, 1];
combination 16
[1, 1;
1, 1];
带有
numpy
和itertools
的一系列解决方案:
[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)]
说明:product
函数返回其输入的笛卡尔乘积。例如,product([0,1],[0,1])
返回一个迭代器,该迭代器包含[0,1]
和[0,1]
的所有可能排列。换句话说,从产品迭代器绘制:
for i, j in product([0, 1], [0, 1]):
实际上相当于运行两个嵌套for循环:
for i in [0, 1]:
for j in [0, 1]:
上面的for循环已经解决了
K,N=(1,0)
的特定情况下的问题。继续上述思路,为了生成向量i
的所有可能的零/一状态,我们需要从迭代器中提取样本,该迭代器相当于深度l
的嵌套for循环,其中l=len(i)
。幸运的是,itertools
通过其repeat
关键字参数提供了实现这一点的框架。对于OP的问题,这个排列深度应该是K*N
,这样在列表理解的每一步中,它都可以被重新塑造成大小合适的numpy数组。更像是一个算法问题-->