枚举二进制变量的所有可能的值组合

假设我有 n 个变量,每个变量都有两个值:0 或 1。如果我想枚举所有可能的值组合,那就是 2^n 个可能的组合。我想知道如何以干净简单的方式生成它?

想象一下 n=4。我们想要生成一个 numpy 数组或类似于以下手动生成的示例的东西。

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

请注意,顺序很重要。第一列总是查看 col1 = 0 的情况,然后移至 col1 = 1 的情况。然后 col2 查看 col2 = 0 且 col1 = 0 的情况,然后 col2 = 1 且 col1 = 0,然后 col2 = 0 给定 col1 = 1,最后 col2 = 1 给定 col1 = 1。依此类推。基本上,无论 n 是多少,我都需要这种排序方法。

这可以通过迭代方法解决吗?

回答

itertools.product([0, 1], repeat=4)将给出一个产生这样一个序列的迭代器。np.array(list(itertools.product([0, 1], repeat=4)))会给你一个 numpy 数组。

  • @flakes "The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order." - [docs](https://docs.python.org/3/library/itertools.html#itertools.product).

以上是枚举二进制变量的所有可能的值组合的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>