1

我希望你能帮助我,我想从以下列表列表中生成组合(作为 nxn 矩阵工作):

   A = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]

但我需要,如果我取第一个列表的第一个数字,然后作为矩阵运算,删除列的其他元素和所选元素的行,然后生成可能的组合

例如,我在第一个列表中选择 1,那么唯一可能生成的组合是:(1,5,9) 和 (1,8,6),因为消除了行和列。

我正在尝试构建一个递归函数来通过删除列和行来实现这一点,问题是我不确定如何使用组合构建列表。

这是我到目前为止:

list = []

def combinations(matrix):
    matrix_rows = len(matrix)
    if matrix_rows == 0:
        # Base case
        return matrix
    else:
        # Recursive case
        # Always select first row
        seq = []
        for index, a in enumerate(matrix[0]):
            E = a
            seq.append(E)
            # Remove i from row of index element a
            new_matrix = remove_row(matrix, 0)
            # Remove j from column index of element a
            new_matrix = remove_column(new_matrix, index)
            # Call again with new matrix
            combinations(new_matrix)
        list.append(seq)
    return list

def remove_row(original_matrix, element_row_index):
    new_matrix = []
    if (len(original_matrix)) >= element_row_index:
        new_matrix = original_matrix[:] 
        new_matrix.remove(original_matrix[element_row_index])
    return new_matrix

def remove_column(matrix, index):
    return [(x[0:index] + x[index + 1:]) for x in matrix]

使用上面的矩阵,我希望有:

A = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]

print("Result: ", combinations(A))

Result: [[1,5,9], [1,6,8], [2,4,9], [2,6,7], [3,4,8], [3,5,7]]

任何人都可以帮助我吗?或者给我一个更好的方法的建议

补充:一个 4x4 的例子:

A = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]

Results: [1,6,11,16], [1,6,12,15],[1,7,10,16], [1,7,12,14], [1,8,10, 15], [1,8,11, 14], ....
4

1 回答 1

4

我认为这可以简单地完成,根本不需要递归。
基本上,您希望range(n)在按顺序遍历列(或分别为行)时选择行(或列)上的所有可能排列。
这是一个简单的解决方案:

from itertools import permutations
import numpy as np

n = 3
x = np.arange(n ** 2).reshape((n, n)) + 1  # so as to fit in with your example
perms = permutations(range(n))
combinations = [list(x[range(n), p]) for p in perms]
print(combinations)
>> [[1, 5, 9], [1, 6, 8], [2, 4, 9], [2, 6, 7], [3, 4, 8], [3, 5, 7]]

但是,如果您没有使用与 numpy 兼容的东西,而是使用列表列表,那么对上述内容进行一些小调整也同样有效:

x = [[1, 'A'], [2, 'B']]  # a "small" case so it's easy to follow
n = len(x)
index_list = range(n)
perms = permutations(index_list)
combinations = [[x[i][p[i]] for i in index_list] for p in perms]
print(combinations)
>> [[1, 'B'], ['A', 2]]

以上假设您仍在使用“方形”数据。这意味着每个内部列表的长度与包含它们的外部列表的长度相同。

希望这会有所帮助,并且它符合您的意思。如果不是,请发表评论,我会纠正任何需要的。我会把它变成一个功能给读者;-)
祝你好运!

于 2018-12-03T20:38:11.977 回答