Skip to main content
 首页 » 编程设计

Python:水平切片矩阵

2024年10月01日9kevingrace

让我们考虑这两个变量:

matrix = [[1, 2, 3, 4], 
          [5, 6, 7, 8], 
          [9, 10, 11, 12]] 
 
list_of_lengths = [2, 1, 1]  

我正在寻找一种方法来获得这个结果:

result = [[[1, 2], 
           [5, 6], 
           [9, 10]], [[3], 
                      [7], 
                      [11]], [[4], 
                              [8], 
                              [12]]] 

确实,我想要三个矩阵作为结果。每个的 j 长度由变量 list_of_lentghts 确定。

我已经编写了一个可行的解决方案,但我想知道是否有更简单的解决方案。这是我的解决方案:

def cut_matrix(matrix, list_of_lengths): 
    result = [] 
    for a_len in list_of_lengths: 
        current_sub_matrix = [] 
        for a_line in matrix: 
            current_new_line = [] 
            for i in range(0, a_len): 
                current_new_line.append(a_line.pop(0)) 
            current_sub_matrix.append(current_new_line) 
        result.append(current_sub_matrix) 
    return result 

请您参考如下方法:

如果知道列偏移i和列数n,就可以使用切片获取列:

[row<b>[i:i+n]</b> for row in matrix]

获取切片。所以你可以简单地使用:

def cut_matrix(matrix, list_of_lengths): 
    result = [] 
    <b>col = 0</b> 
    for a_len in list_of_lengths: 
        result.append(<b>[row[col:col+a_len] for row in matrix]</b>) 
        <b>col += a_len</b> 
    return result

它产生:

>>> cut_matrix(matrix,list_of_lengths) 
[[[1, 2], [5, 6], [9, 10]], [[3], [7], [11]], [[4], [8], [12]]] 

这也比使用 .pop(0) 更快,因为从前面弹出是在 O(n) 中完成的(所以弹出所有元素需要 O(n2) 而切片所有元素在 O(n) 中完成。最后,它保留了原始的矩阵,因此更具声明性。