生成 w x h 矩阵中 n 个条目的所有排列

Generate all permutations of n entries in a w x h matrix

我想生成 w x h 矩阵中 n 个条目的所有排列: 具有 2x2 矩阵且 n = 1 的示例:

| 1 0 |
| 0 0 |

| 0 1 |
| 0 0 |

| 0 0 |
| 1 0 |

| 0 0 |
| 0 1 |

具有 3x3 矩阵且 n = 2(部分)的示例:

| 0 0 1|
| 0 0 1|
| 0 0 0|

| 1 0 0|
| 0 0 1|
| 0 0 0|

...

我想避免使用 numpy,所以我认为 itertool 是可行的方法。 我正在查看一维解决方案,但我得到的只是一些稍微不同的东西,比如 itertools.product 用固定数量的值迭代,例如

itertools.product([0,'n'],repeat=6)

[(0, 0, 0, 0, 0, 0),....('n', 'n', 'n', 'n', 'n', 'n')]

任何提示将不胜感激

w * h 个可用位置,您要在其中放置 n 个 1,其余用 0 填充。

您可以使用 itertools.combinations:

创建 n 1 的所有可能组合
>>> w = 2
>>> h = 2
>>> n = 2
>>> list(itertools.combinations(range(w * h), n))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

要从位置元组之一创建实际矩阵(作为 1 和 0 的列表),例如,您可以使用列表理解:

>>> positions = (1, 3)
>>> [1 if i in positions else 0 for i in range(w * h)]
[0, 1, 0, 1]

对于非常大的 n 查找 i in positions 变得低效,最好将其更改为如下函数:

def create_matrix(positions):
    matrix = [0] * w * h
    for i in positions:
        matrix[i] = 1
    return matrix

现在你可以把所有东西放在一起了:

>>> [[1 if i in p else 0 for i in range(w * h)]
...  for p in itertools.permutations(range(w * h), n)]
[[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [1, 1, 0, 0], [0, 1, 1, 0], [0, 1, 0, 1],
 [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]]

或者,如果您使用 create_matrix 函数:

>>> [create_matrix(p) for p in itertools.permutations(range(w * h), n)]