algorithm - 将矩阵分解为更小的子列表
问题描述
我无法理解如何实现这一目标。更具体地说,我想打破以下矩阵
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 这样的库的情况下做到这一点?是否可以?
解决方案
如果我们编写一个辅助函数来将一个 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)
]
推荐阅读
- c# - 如何通过按钮刷新图片框?
- python - 每次使用 Python 创建新的 Zip 文件
- flutter - Flutter:在 Bloc 转换之间的小部件中保存状态
- java - Java Reactor:在另一个线程中登录 Mono.fromSupplier()
- apollo - 使用 client.readFragment() 从 Apollo 缓存中读取片段
- swift - 如何交换两个视图框架并在它们的视图层次结构中快速交换它们?
- php - 检查 strlen 并仅在完成时发送数据
- mysql - 根据切片中的键序列对数据进行排序 Go
- delphi - Delphi,Object Pascal,写入注册表不起作用
- java - Vertx 服务接口重构