Efficient way to shift 2D-matrices in both directions?

前端 未结 4 1713
离开以前
离开以前 2021-02-07 15:29

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 operatio

4条回答
  •  [愿得一人]
    2021-02-07 16:01

    Maybe something like this using numpy:

    def shift(x, direction='up'):
        if direction == 'up':
            temp = range(x.shape[0])
            indicies = temp[1:] + [temp[0]]
            return x[indicies]
        elif direction == 'left':
            temp = range(x.shape[1])
            indicies = temp[1:] + [temp[0]]
            return x[:, indicies]
        else:
            print 'Error direction not known'
    

    Result:

    >>> shift(l, direction='up')
    array([[2, 5, 2],
           [3, 3, 3],
           [1, 1, 1]])
    >>> shift(l, direction='left')
    array([[1, 1, 1],
           [5, 2, 2],
           [3, 3, 3]])
    >>> shift(l, direction='to the moon')
    Error direction not known
    

提交回复
热议问题