Python 中的柱状排列

Columnar permutations in Python

我怎样才能找到矩阵中各列的所有排列。例如 - 如果我有一个像这样的 6x6 方形矩阵:

   a   b   c   d   e   f

1: 75  62  82  85  91  85

2: 64  74  74  82  74  64

3: 85  81  91  83  91  62

4: 91  63  81  75  75  72

5: 81  91  74  74  91  63

6: 91  72  81  64  75  72

每列中的所有数字 - abcdef - 在通过柱状排列移动时将保留在该列中。

这是我表示您的数据的方式...您似乎想要行,但您想要的排列是在列中。这是列表的列表,首先是行:

row_matrix = [[75, 62, 82, 85, 91, 85],
 [64, 74, 74, 82, 74, 64],
 [85, 81, 91, 83, 91, 62],
 [91, 63, 81, 75, 75, 72],
 [81, 91, 74, 74, 91, 63],
 [91, 72, 81, 64, 75, 72]]

您可以使用 numpy 通过将列表转换为 numpy 数组并应用 .T 轻松转置(行 x 列)-->(列 x 行)的二维数组。我将在此处使用它,但会使用 .tolist() 将内容推回到 Python 列表中,以简化您的操作。

import numpy as np

column_matrix = np.array(row_matrix).T.tolist()

接下来,您需要列号列表 -- 在您的情况下为 0 到 5。我使用整数而不是将它们称为“a”到“f”以方便在下面进行索引......你可以稍后将字母名称分配给它们(......但是如果你宁愿一直保留该标签,你可以使用 Python 词典代替):

columns = list(range(len(column_matrix)))

# print(columns)
# shows --> [0, 1, 2, 3, 4, 5]

对于排列,有一个用于生成它们的内置库,作为 itertools 的一部分。列表列表的主索引现在是列号,因此如果我们生成列号顺序的排列,我们可以从中构建所有二维矩阵。之后,您可以再次转置它们以将其恢复为原始的按行数据结构:

from itertools import permutations

all_permutations = []
for perm in itertools.permutations(columns):
    shuffled_column_matrix = []
    for idx in perm:
        shuffled_column_matrix.append(column_matrix[idx])
    all_permutations.append( np.array(shuffled_column_matrix).T.tolist() )

以上可以使用列表理解以更紧凑的方式完成:

#all_permutations = []
#for perm in itertools.permutations(columns):
#    shuffled_column_matrix = np.array( [ column_matrix[idx] for idx in perm ] )
#    all_permutations.append( shuffled_column_matrix.T.tolist() )  

完成后 all_permutations 是所有按列排列的列表,表示为类似于输入的按行矩阵。