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

前端 未结 4 1714
离开以前
离开以前 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 15:51

    This is a generic version you can rotate it in all four directions, any number of times

    l = [[1,1,1],
         [2,5,2],
         [3,3,3]]
    
    def shift(direction, count, myList):
        myLen = len(myList)
        if direction == "up":
            return [myList[i % myLen] for i in range(count, count + myLen)]
        elif direction == "down":
            return [myList[-i] for i in range(count, count - myLen, -1)]
        elif direction == "left":
            tlist = zip(*myList)
            return map(list, zip(*[tlist[i % myLen] for i in range(count, count + myLen)]))
        elif direction == "right":
            tlist = zip(*myList)
            return map(list, zip(*[tlist[-i] for i in range(count, count - myLen, -1)]))
    
    print shift("up", 1, l)
    print shift("up", 2, l)
    print shift("down", 2, l)
    print shift("down", 1, l)
    print shift("left", 1, l)
    print shift("right", 1, l)
    

    Output

    [[2, 5, 2], [3, 3, 3], [1, 1, 1]]
    [[3, 3, 3], [1, 1, 1], [2, 5, 2]]
    [[2, 5, 2], [3, 3, 3], [1, 1, 1]]
    [[3, 3, 3], [1, 1, 1], [2, 5, 2]]
    [[1, 1, 1], [5, 2, 2], [3, 3, 3]]
    [[1, 1, 1], [2, 2, 5], [3, 3, 3]]
    

提交回复
热议问题