假設我有在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這樣的擴展庫?
假設我有在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][:h/2] for i in range(w/2)]
top_right = [a[i][h/2:] for i in range(w/2)]
bot_left = [a[i][:h/2] for i in range(w/2, w)]
bot_right = [a[i][h/2:] for i in range(w/2, w)]
完美。謝謝一堆! – mountaineer1980
寫得很好的代碼。謝謝 ! – CyprUS
>>> a = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
>>> x = map(lambda x:x[:2], a)
>>> x
[[1, 2], [5, 6], [9, 10], [13, 14]]
>>> y = map(lambda x: x[2:], a)
>>> y
[[3, 4], [7, 8], [11, 12], [15, 16]]
>>> x[:2] + y[:2] + x[2:] + y[2:]
[[1, 2], [5, 6], [3, 4], [7, 8], [9, 10], [13, 14], [11, 12], [15, 16]]
如果你需要做到這一點,我想你可能應該使用numpy – wim