2016-02-11 160 views
0

有人可以告訴我爲什麼我得到這個錯誤嗎?爲什麼超出範圍?

result[i][j+1]=X[i][j] 
IndexError: list assignment index out of range 

這裏是我的代碼:

def matrixTranspose(X): 
    result=[[0 for k in range (len(X))] for l in range (len(X[0]))] 
    for i in range(len(X)): 
     for j in range (len(X[0])): 
      result[i][j+1]=X[i][j] 
    return result 


m1=[] 
r=input("enter The no. of rows:") 
c=input("enter The no. of columns:") 
s=[[0 for i in range (c)]for j in range (r)] 
for i in range (r): 
row=[] 
for j in range (c): 
    x=input("Enter Value") 
    row.append(x) 
m1.append(row) 


print m1 
m2=matrixTranspose(m1) 
print m2 
+0

我認爲用於轉置矩陣的規範解決方案是'zip(* X)'。但我明白需要讓自己的版本適合教育目的。 – Droogans

回答

1

你不能索引resultlen(X[0])+1,因爲它的尺寸是由len(X[0])len(X)。您的matrixTranpose功能似乎也沒有采取X的轉置。推測你的意思是:

def matrixTranspose(X): 
    result=[[0 for k in range (len(X))] for l in range (len(X[0]))] 
    for i in range(len(X)): 
     for j in range (len(X[0])): 
      result[j][i]=X[i][j] 
    return result 
+0

那麼如果我想旋轉矩陣90度? –

+0

這不是轉置。如果你想旋轉90度的矩陣,這個網站上有很多答案告訴你如何做到這一點。 – xnx

相關問題