Python:水平切片矩阵 让我们考虑这两个变量: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] list_of_lengths = [2, 1, 1]
我正在寻找一种方法来获得此结果:Python:水平切片矩阵 让我们考虑这两个变量: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] list_of_lengths = [2, 1, 1],python,list,matrix,slice,Python,List,Matrix,Slice,我正在寻找一种方法来获得此结果: result = [[[1, 2], [5, 6], [9, 10]], [[3], [7], [11]], [[4], [8], [12]]] 事实上,我想要三个矩阵作为结果。每个变量的j长度由变量列表决定 我
result = [[[1, 2],
[5, 6],
[9, 10]], [[3],
[7],
[11]], [[4],
[8],
[12]]]
事实上,我想要三个矩阵作为结果。每个变量的j长度由变量列表决定
我已经写了一个有效的解决方案,但我想知道是否有更简单的解决方案。以下是我的解决方案:
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[i:i+n] for row in matrix]
这也将比使用
.pop(0)
的速度更快,因为从前面弹出是在O(n)中完成的(因此弹出所有元素需要O(n2),而切片所有元素是在O(n)中完成的)。最后,它保留了原始的矩阵
,因此更具声明性。您是否接受使用numpy
库的解决方案?如果没有,请移除标签。
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]]]