【问题标题】:How to generate all possible combinations of 0-1 matrix in Python?如何在 Python 中生成 0-1 矩阵的所有可能组合?
【发布时间】:2016-10-10 07:40:25
【问题描述】:

如何生成大小为 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, 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]; 

【问题讨论】:

标签: python combinations


【解决方案1】:

numpyitertools 的单线解决方案:

[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 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多