(在下面的例子中6×6)有nxn的的一個特別的方式填充矩陣僅與0和1:調整大小的矩陣
old_matrix=[[0,0,0,1,1,0],
[1,1,1,1,0,0],
[0,0,1,0,0,0],
[1,0,0,0,0,1],
[0,1,1,1,1,0],
[1,0,0,1,1,0]]
欲調整它以特定的方式。以(2x2)子矩陣和檢查是否有更多的1或零。這意味着新的矩陣將是(3x3)如果有多於1個子矩陣,則將在新矩陣中分配1個值。否則,(如果有或更少)其新值將爲0.
new_matrix=[[0,1,0],
[0,0,0],
[0,1,0]]
我試圖通過使用大量的whiles來實現此目的。但它似乎並不奏效。這是我走到這一步:
def convert_track(a):
#converts original map to a 8x8 tile Track
NEW_TRACK=[]
w=0 #matrix width
h=0 #matrix heigth
t_w=0 #submatrix width
t_h=0 #submatrix heigth
BLACK=0 #number of ones in submatrix
WHITE=0 #number of zeros in submatrix
while h<=6:
while w<=6:
l=[]
while t_h<=2 and h<=6:
t_w=0
while t_w<=2 and w<=6:
if a[h][w]==1:
BLACK+=1
else:
WHITE+=1
t_w+=1
w+=1
h+=1
t_h+=1
t_w=0
t_h+=1
if BLACK<=WHITE:
l.append(0)
else:
l.append(1)
BLACK=0
WHITE=0
t_h=0
NEW_TRACK.append(l)
return NEW_TRACK
引發錯誤列表索引超出範圍或返回列表
[[0]]
有更簡單的方式來實現這一目標?我究竟做錯了什麼?
有效的子矩陣將是第一個列表或行的前兩個元素,以及第二個列表或行的前兩個元素:[[0,0],[1,1]] –