zoukankan      html  css  js  c++  java
  • Python之2维list转置、旋转及其简单应用

     给一个矩阵,顺时针旋转顺序输出其元素,例如:

    对于矩阵:

    [ 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))

    输出为:

  • 相关阅读:
    C#开发规范
    Win32API使用技巧 -- 置顶应用
    Windows开发常用快捷键
    MarkDown简单语法回顾
    样本分布
    复变函数
    set theory
    Oscar的数理统计笔记本
    Oscar的拓扑笔记本
    c语言总结
  • 原文地址:https://www.cnblogs.com/huangshiyu13/p/7838411.html
Copyright © 2011-2022 走看看