【问题标题】:Python: slice a matrix horizontallyPython:水平切片矩阵
【发布时间】:2017-07-26 03:41:44
【问题描述】:

让我们考虑这两个变量:

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

【问题讨论】:

  • 您是否接受使用numpy 库的解决方案?如果没有,请删除numpy 标签。

标签: python list matrix slice


【解决方案1】:

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

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

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

def cut_matrix(matrix, list_of_lengths):
    result = []
    col = 0
    for a_len in list_of_lengths:
        result.append([row[col:col+a_len] for row in matrix])
        col += a_len
    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 sup>) 而切片所有元素是在 O(n)) 中完成的。最后,它保留了原始的matrix,因此更具声明性

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多