Rotating a two-dimensional array in Python

后端 未结 7 1344
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 19:38

In a program I\'m writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job:

相关标签:
7条回答
  • 2020-11-28 20:04

    Just an observation. The input is a list of lists, but the output from the very nice solution: rotated = zip(*original[::-1]) returns a list of tuples.

    This may or may not be an issue.

    It is, however, easily corrected:

    original = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]
                ]
    
    
    def rotated(array_2d):
        list_of_tuples = zip(*array_2d[::-1])
        return [list(elem) for elem in list_of_tuples]
        # return map(list, list_of_tuples)
    
    print(list(rotated(original)))
    
    # [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
    

    The list comp or the map will both convert the interior tuples back to lists.

    0 讨论(0)
提交回复
热议问题