给一个矩阵,顺时针旋转顺序输出其元素,例如:
对于矩阵:
[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
输出为:
1,2,3,6,9,8,7,4,5
def transpose(matrix): return zip(*matrix) def rotate(matrix): return zip(*matrix)[::-1] def rotatePrint(matrix): import copy matrix = copy.deepcopy(matrix) return matrix and list(matrix.pop(0)) + rotatePrint(rotate(matrix)) ######### Test ############# def printMatrix(matrix): for row in matrix: print ' '.join( str(i) for i in row) matrix = [ [1,2,3], [4,5,6], [7,8,9]] print 'original:' printMatrix(matrix) print 'rotate print:',rotatePrint(matrix) print 'transpose:' printMatrix( transpose(matrix) ) print 'rotate:' printMatrix( rotate(matrix))
输出为: