matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
顺序旋转
代码语言:javascript复制def order_rotate(matrix):
res = list(zip(*matrix))
res = [alist[::-1] for alist in res]
return res
res1 = order_rotate(matrix)
print(res1)
[(9, 5, 1), (10, 6, 2), (11, 7, 3), (12, 8, 4)]
逆序旋转
代码语言:javascript复制def reverse_rotate(matrix):
res = list(zip(*matrix))[::-1]
return res
res2 = reverse_rotate(matrix)
print(res2)
[(4, 8, 12), (3, 7, 11), (2, 6, 10), (1, 5, 9)]
应用:顺序打印数组
代码语言:javascript复制def print_matrix(matrix):
res = []
while len(matrix) > 0:
res.extend(matrix[0])
matrix = list(zip(*matrix[1:]))[::-1]
return res
res = print_matrix(matrix)
print(res)
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]