2015-06-17 31 views
0

我想知道如何創建N大小的矩陣,其中矩陣的索引將是字典中的鍵。 我假設python有至少支持這個矩陣的選項,以防萬一每個鍵的值都是邏輯無符號整數(或者屏蔽成一個)我可以訪問矩陣中的任何單元格 通過使用dict [key]而不是索引。用字典創建N維矩陣 - python 2.7

回答

0

下面的例子應該幫助,它會創建大小爲2的2維矩陣×3:

d = { 
    0: {0: 'a', 1: 'b', 2: 'c'}, 
    1: {0: 'd', 1: 'e', 2: 'f'}, 
} 
from pprint import pprint 
pprint(d) 

# Using keys as indices 
print d[1][2] 

# output 
{0: {0: 'a', 1: 'b', 2: 'c'}, 1: {0: 'd', 1: 'e', 2: 'f'}} 
f 
0

在這裏,我會怎麼做:

def showMatrixForm(matrix): 
    matshape="" 
    for row in range(1,matrix["rows"]+1): 
     for column in range(1,matrix["columns"]+1): 
      spaces=5-len(str(matrix[str(row)+","+str(column)])) 
      matshape+="".join([" " for space in range(spaces)])+str(matrix[str(row)+","+str(column)]) 
     matshape+="\n" 
    return matshape 



matrix={} 

rows=10 
columns=10 

matrix["rows"]=rows 
matrix["columns"]=columns 

i=0 
for row in range(1,rows+1): 
    for column in range(1,columns+1): 
     i+=1 
     matrix[str(row)+","+str(column)]=i 

print(showMatrixForm(matrix)) 
''' 
    1 2 3 4 5 6 7 8 9 10 
    11 12 13 14 15 16 17 18 19 20 
    21 22 23 24 25 26 27 28 29 30 
    31 32 33 34 35 36 37 38 39 40 
    41 42 43 44 45 46 47 48 49 50 
    51 52 53 54 55 56 57 58 59 60 
    61 62 63 64 65 66 67 68 69 70 
    71 72 73 74 75 76 77 78 79 80 
    81 82 83 84 85 86 87 88 89 90 
    91 92 93 94 95 96 97 98 99 100 
''' 

print(matrix["1,2"],matrix["8,4"],matrix["5,7"]) 
''' 
(2, 74, 47) 
''' 

我希望這會幫助你。