3
简单的2维数组允许在O(1)时间内交换矩阵中的行(或列)。有没有一种有效的数据结构,可以在O(1)时间内交换矩阵的行和列?矩阵数据结构
简单的2维数组允许在O(1)时间内交换矩阵中的行(或列)。有没有一种有效的数据结构,可以在O(1)时间内交换矩阵的行和列?矩阵数据结构
您必须将矩阵存储为行列表或列列表。它可以交换行或交换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]
也许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]])
而且numpy在这里具有转置属性'b.T',以实际上交换列和行。 – u0b34a0f6ae 2009-11-06 09:18:49
它可以使用Python的切片符号,但它不允许您在O(1)时间交换列 – ooboo 2009-11-06 12:54:22