在两个方向上移动2D矩阵的有效方法? [英] Efficient way to shift 2D-matrices in both directions?
问题描述
给出一个二维矩阵,例如
Given a two dimensional matrix, e.g.
l = [[1,1,1],
[2,5,2],
[3,3,3]])
在列和行上执行移位操作的最有效方法是什么?
What is the most efficient way of implementing a shift operation on columns and rows?
例如
shift('up', l)
[[2, 5, 2],
[3, 3, 3],
[1, 1, 1]]
但是
shift('left', l)
[[1, 1, 1],
[5, 2, 2],
[3, 3, 3]]
由于此答案,我在两个深度上都使用了collections.deque
,但同时出现了向上"或向下" 只需要移位1个,向左"或向右"需要N个移位(我的实现是对每行使用for循环).
I'm using collections.deque
on both depths because of this answer but while a 'up' or 'down' only requires 1 shift, a 'left' or 'right' requires N shifts (my implementation is using a for cycle for each row).
在C语言中,我认为可以使用指针算法来改善这一点(请参见例如此答案).
In C I think this can be improved using pointer arithmetic (see e.g. this answer).
有没有更好的pythonic方法?
Is there a better pythonic way?
- 高效是指是否有避免N频移的方法.
- 我们可以假设矩阵是平方的.
- 可以就班了.
感谢martineau指出了问题的这些要点. 抱歉,我之前没有指出.
Thanks to martineau for pointing out these important points of the question. I'm sorry I didn't pointed them out before.
推荐答案
Numpy提供了一种名为roll()的方法来移动条目.
Numpy provides a method called roll() to shift entries.
>>> 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]]
我猜想 Numpy 与大多数解决方案相比将非常有效
就矩阵运算而言,您将不会受到二维矩阵的束缚.
I guess that Numpy will be pretty efficient compared to most solutions
in terms of matrix operations and you won't be bound to a 2 dimensional matrix.
这篇关于在两个方向上移动2D矩阵的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!