How do you rotate a two dimensional array?

后端 未结 30 3567
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:40

    Python:

    rotated = list(zip(*original[::-1]))
    

    and counterclockwise:

    rotated_ccw = list(zip(*original))[::-1]
    

    How this works:

    zip(*original) will swap axes of 2d arrays by stacking corresponding items from lists into new lists. (The * operator tells the function to distribute the contained lists into arguments)

    >>> list(zip(*[[1,2,3],[4,5,6],[7,8,9]]))
    [[1,4,7],[2,5,8],[3,6,9]]
    

    The [::-1] statement reverses array elements (please see Extended Slices or this question):

    >>> [[1,2,3],[4,5,6],[7,8,9]][::-1]
    [[7,8,9],[4,5,6],[1,2,3]]
    

    Finally, combining the two will result in the rotation transformation.

    The change in placement of [::-1] will reverse lists in different levels of the matrix.

提交回复
热议问题