假设我在 python 中有以下矩阵:
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
我想把它分成以下矩阵(或象限/角):
[[1,2], [5,6]]
[[3,4], [7,8]]
[[9,10], [13,14]]
[[11,12], [15,16]]
python 中的标准切片运算符是否支持此操作,或者是否有必要使用像 numpy 这样的扩展库?
最佳答案
如果您总是使用 4x4 矩阵:
a = [[1 ,2 , 3, 4],
[5 ,6 , 7, 8],
[9 ,10,11,12],
[13,14,15,16]]
top_left = [a[0][:2], a[1][:2]]
top_right = [a[0][2:], a[1][2:]]
bot_left = [a[2][:2], a[3][:2]]
bot_right = [a[2][2:], a[3][2:]]
您也可以对任意大小的矩阵执行相同的操作:
h = len(a)
w = len(a[1])
top_left = [a[i][:w // 2] for i in range(h // 2)]
top_right = [a[i][w // 2:] for i in range(h // 2)]
bot_left = [a[i][:w // 2] for i in range(h // 2, h)]
bot_right = [a[i][w // 2:] for i in range(h // 2, h)]
关于python - 将python矩阵切成象限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811981/