2009-11-06 83 views
3

簡單的2維數組允許在O(1)時間內交換矩陣中的行(或列)。有沒有一種有效的數據結構,可以在O(1)時間內交換矩陣的行和列?矩陣數據結構

回答

4

您必須將矩陣存儲爲行列表或列列表。它可以交換行或交換O(1)中的列。

但是,您可以在其上添加另一個圖層來處理列順序,以便您可以對O(1)中的列重新排序。

所以每次訪問,你需要做的:

x = data[row][colorder[col]] 

交換行爲:

data[row1], data[row2] = data[row2], data[row1] 

而交換的列:

colorder[col1], colorder[col2] = colorder[c2], colorder[c1] 
0

也許numpy array可以幫助您 - 它允許訪問行和列,並且它非常高效(這是scipy的基本數據類型)

>>> def f(x,y): 
...   return 10*x+y 
... 
>>> b = fromfunction(f,(5,4),dtype=int) 
>>> b 
array([[ 0, 1, 2, 3], 
     [10, 11, 12, 13], 
     [20, 21, 22, 23], 
     [30, 31, 32, 33], 
     [40, 41, 42, 43]]) 
>>> b[:,1]         # the second column of b 
array([ 1, 11, 21, 31, 41]) 
>>> b[1:3,:]        # the second and third row of b 
array([[10, 11, 12, 13], 
     [20, 21, 22, 23]]) 
+0

而且numpy在這裏具有轉置屬性'b.T',以實際上交換列和行。 – u0b34a0f6ae 2009-11-06 09:18:49

+0

它可以使用Python的切片符號,但它不允許您在O(1)時間交換列 – ooboo 2009-11-06 12:54:22