矩阵数据结构

时间:2009-11-06 08:18:19

标签: python matrix

简单的二维数组允许在O(1)时间内交换矩阵中的行(或列)。是否有一个有效的数据结构,允许在O(1)时间内交换矩阵的行和列?

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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]])