Python: 水平切片矩阵
Python: slice a matrix horizontally
让我们考虑这两个变量:
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) 中完成的。最后,它完整地保留了原始 matrix
,因此更具 声明性 。
让我们考虑这两个变量:
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) 中完成的。最后,它完整地保留了原始 matrix
,因此更具 声明性 。