首页 > 解决方案 > 将矩阵分解为更小的子列表

问题描述

我无法理解如何实现这一目标。更具体地说,我想打破以下矩阵

matrix = [[7, 9, 1, 8, 9, 1],
         [4, 2, 1, 2, 1, 5],
         [3, 2, 3, 1, 2, 3],
         [7, 9, 11, 6, 4, 8],
         [8, 9, 22, 3, 1, 9],
         [1, 1, 1, 1, 1, 1]]

进入:

[[7, 9,
  4, 2],
[1, 8,
 1, 2],
[9, 1,
 1, 5],
[3, 2,
 7, 9],
[3, 1,
 11, 6],
[2, 3,
 4, 8],
[8, 9,
 1, 1],
[22, 3,
 1, 1],
[1, 9,
 1, 1]]

或者等价地,

[[7, 9, 4, 2],
[1, 8, 1, 2],
[9, 1, 1, 5],
[3, 2, 7, 9],
[3, 1, 11, 6],
[2, 3, 4, 8],
[8, 9, 1, 1],
[22, 3, 1, 1],
[1, 9, 1, 1]]

这是我尝试做的事情:

def split([[]]) -> [[]]
  split_matrix = []
  temp_map = []
  row_limit, col_limit = 2, 2

  for row in range(len(elevation_map)):
      for col in range(len(elevation_map)):
            elevation = elevation_map[row][col]
          if row < row_limit and col < col_limit:
              temp_map.append(elevation)
  split_matrix.append(temp_map)
  return split_matrix

但是,我没有运气这样做。

有没有办法在不使用像 numpy 这样的库的情况下做到这一点?是否可以?

标签: algorithm

解决方案


如果我们编写一个辅助函数来将一个 2x2 子矩阵提取到一个列表中,那么解决方案将会更加简洁。之后,这是一个简单的列表推导,遍历每个子矩阵左上角的坐标。

def split_matrix(matrix, rows=2, cols=2):
    def helper(i, j):
        out = []
        for row in matrix[i:i+rows]:
            out.extend(row[j:j+cols])
        return out

    width, height = len(matrix[0]), len(matrix)
    return [
        helper(i, j)
        for i in range(0, height, rows)
        for j in range(0, width, cols)
    ]

推荐阅读