繁体   English   中英

二维矩阵的置换

[英]Permutation of 2D matrix

我希望能够在 python 中生成二维数组的所有唯一排列并保持顺序。 假设我有一个二维矩阵[[1, 2, 3], [4, 5, 6]] 预期结果应为 8 x 3 格式的[[1, 2, 3], [1, 2, 6], [1, 5, 3], [1, 5, 6], [4, 2, 3], [4, 2, 6], [4, 5, 3], [4, 5, 6]]

谢谢

转置数组,然后使用itertools.product

from itertools import product

list(map(list, product(*zip(*data))))

这输出:

[[1, 2, 3], [1, 2, 6], [1, 5, 3], [1, 5, 6], [4, 2, 3], [4, 2, 6], [4, 5, 3], [4, 5, 6]]

您可以使用zip转置 2D listitertools.product

>>> from itertools import product
>>> lst = [[1, 2, 3], [4, 5, 6]]
>>> list(product(*(zip(*lst))))
# If you want to get each `tuple` as `list`
# >>> list(map(list, product(*zip(*lst))))

[(1, 2, 3),
 (1, 2, 6),
 (1, 5, 3),
 (1, 5, 6),
 (4, 2, 3),
 (4, 2, 6),
 (4, 5, 3),
 (4, 5, 6)]

带有 product 的方法将是执行此操作的最易读的方法,但由于您的问题被标记为 ,因此您可以仅使用 Numpy 方法执行此操作。

1. 没有预期顺序的排列

如果顺序对您不重要,您可以使用此方法。 这使用np.meshgridnp.stack与一些.reshape来获得你需要的排列,减去你期望的顺序。

import numpy as np

lst = [[1, 2, 3], [4, 5, 6]]

arr = np.array(lst)
np.stack(np.meshgrid(*arr.T),-1).reshape(-1,3)
array([[1, 2, 3],
       [1, 2, 6],
       [4, 2, 3],
       [4, 2, 6],
       [1, 5, 3],
       [1, 5, 6],
       [4, 5, 3],
       [4, 5, 6]])

2. 具有预期顺序的排列

让订单工作有点“hacky”,但通过简单的列重新排序对上述数组进行小的修改可以用几乎相同的代码解决这个问题。

import numpy as np

lst = [[1, 2, 3], [4, 5, 6]]
order = [1,0,2]

arr = np.array(lst)[:,order]
np.stack(np.meshgrid(*arr.T),-1).reshape(-1,3)[:,order]
array([[1, 2, 3],
       [1, 2, 6],
       [1, 5, 3],
       [1, 5, 6],
       [4, 2, 3],
       [4, 2, 6],
       [4, 5, 3],
       [4, 5, 6]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM