gpt4 book ai didi

python - 如何在 Python 中生成 0-1 矩阵的所有可能组合?

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:26 24 4
gpt4 key购买 nike

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

最佳答案

使用 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,这样它就可以在列表推导的每个步骤中被 reshape 为适当大小的 numpy 数组。

关于python - 如何在 Python 中生成 0-1 矩阵的所有可能组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39948902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com