【发布时间】: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 标签。