2016-11-25 183 views
2

要求:創建列表的列表。修改元素列表中的

定義函數createMatDimXDim(dim) 該函數接收的正整數數目大於2或相等,並且返回尺寸的方陣暗淡X暗淡,其中所述內容是數字,其等於行號乘以10加上列號。

預期輸出:

print (createMatDimXDim (4)) 
[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] 

我的代碼:

def createMatDimXDim (dim): 
    lis=[[0] for i in range(dim)] 
    for i in range(dim): 
     lis[i][0]=i*10 
     for i in range(dim): 
      lis[i].append(int(lis[i][0])+1) 
    return lis 

輸出繼電器我的代碼:

[[0, 1, 1, 1, 1], [10, 1, 11, 11, 11], [20, 1, 1, 21, 21], [30, 1, 1, 1, 31]] 

我想這樣做:

lis[i].append(int(lis[i][i-1])+1) 

但它給了我一個IndexError

回答

4
def createMatDimXDim (dim): 
    lis=[[0] for i in range(dim)] 
    for i in range(dim): 
     lis[i][0]=i*10 
     for j in range(dim-1):    # for the nested loop you need to use a new 
              # variable j 
      lis[i].append(int(lis[i][j])+1) 
    return lis 

createMatDimXDim(4) 
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] 

另一種選擇與列表理解:

dim = 4 
[[i * 10 + j for j in range(dim)] for i in range(dim)] 
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] 
2

您可以使用2D列表理解。

def createMatDimXDim(dim): 
    return [[j for j in range(i*10, i*10+dim)] for i in range(dim)] 
createMatDimXDim(4) 

輸出:

[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] 
2
def createMatDimXDim(dim): 
    return [[j for j in range(i*10, i*10+dim)] for i in range(dim)] 
1

一個簡單易懂的方式做是:

def createMatDimXDim (dim): 
    lis=[[0] for i in range(dim)] 
    for i in range(dim): 
     lis[i][0]=i*10 
     for j in range(dim-1):          
      lis[i].append(int(lis[i][j])+1) 
    return lis 

createMatDimXDim(4) 

輸出:

[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]