在两个方向上移动2D矩阵的有效方法?

Jor*_*tao 13 python matrix

给定二维矩阵,例如

l = [[1,1,1],
     [2,5,2],
     [3,3,3]])
Run Code Online (Sandbox Code Playgroud)

在列和行上实现移位操作的最有效方法是什么?

例如

shift('up', l) 

[[2, 5, 2],
 [3, 3, 3],
 [1, 1, 1]]
Run Code Online (Sandbox Code Playgroud)

shift('left', l) 

[[1, 1, 1],
 [5, 2, 2],
 [3, 3, 3]]
Run Code Online (Sandbox Code Playgroud)

collections.deque由于这个答案,我在两个深度上使用但是"向上"或"向下"只需要1个移位,"向左"或"向右"需要N个移位(我的实现是每行使用一个for循环).

在CI中,可以使用指针算法来改进这一点(参见例如此答案).

有更好的pythonic方式吗?

编辑:

  • 通过有效我的意思是,如果有一种方法可以避免N个班次.
  • 我们可以假设矩阵是平方的.
  • 转变可以到位.

感谢martineau指出了问题的这些重点.对不起我之前没有指出过.

Nim*_*avi 28

Numpy提供了一个名为roll()的方法来移动条目.

>>> import numpy as np
>>> x = np.arange(9)
>>> x = x.reshape(3, 3)
>>> print(x)

[[0 1 2]
 [3 4 5]
 [6 7 8]]

>>> x = np.roll(x, -1, axis=0) # up
>>> print(x)

[[3 4 5]
 [6 7 8]
 [0 1 2]]

>>> x = np.roll(x, 1, axis=0) # down
>>> print(x)

[[0 1 2]
 [3 4 5]
 [6 7 8]]

>>> x = np.roll(x, 2, axis=1) # right
>>> print(x)

[[1 2 0]
 [4 5 3]
 [7 8 6]]

>>> x = np.roll(x, -2, axis=1) # left
>>> print(x)    

[[0 1 2]
 [3 4 5]
 [6 7 8]]
Run Code Online (Sandbox Code Playgroud)

我猜Numpy
在矩阵运算方面 与大多数解决方案相比都非常有效,你不会受到二维矩阵的束缚.