Python3实现的旋转矩阵图像算法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python3实现的旋转矩阵图像算法。分享给大家供大家参考,具体如下:

问题:

给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

方案一:先按X轴对称旋转, 再用zip()解压,最后用list重组。

# -*- coding:utf-8 -*-
#! python3
class Solution:
  def rotate(self, matrix):
    """
    :type matrix: List[List[int]]
    :rtype: void Do not return anything, modify matrix in-place instead.
    """
    matrix[:] = map(list, zip(*matrix[: : -1]))
    return matrix
if __name__ == '__main__':
  # 测试代码
  matrix = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12],
    [13,14,15,16]
  ]
  solution = Solution()
  result = solution.rotate(matrix)
  print(result)

运行结果:

[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]

方案二:找到规律,用原矩阵数据 赋值

# -*- coding:utf-8 -*-
#! python3
class Solution:
  def rotate(self, matrix):
    """
    :type matrix: List[List[int]]
    :rtype: void Do not return anything, modify matrix in-place instead.
    """
    m = matrix.copy()
    n = len(matrix)
    for i in range(n):
      matrix[i] = [m[j][i] for j in range(n - 1, -1, -1)]
    return
if __name__ == '__main__':
  # 测试代码
  matrix = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12],
    [13,14,15,16]
  ]
  solution = Solution()
  result = solution.rotate(matrix)
  print(result)

运行结果:

[[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python打开文件并获取文件相关属性的方法

本文实例讲述了python打开文件并获取文件相关属性的方法。分享给大家供大家参考。具体分析如下: 下面的代码通过open函数打开文件,并输出文件名、打开状态、打开模式等属性 #!/u...

python 多进程并行编程 ProcessPoolExecutor的实现

使用 ProcessPoolExecutor from concurrent.futures import ProcessPoolExecutor, as_completed im...

Python向Excel中插入图片的简单实现方法

Python向Excel中插入图片的简单实现方法

本文实例讲述了Python向Excel中插入图片的简单实现方法。分享给大家供大家参考,具体如下: 使用Python向Excel文件中插入图片,这个功能之前学习xlwt的时候通过xlwt模...

pandas实现将日期转换成timestamp

pandas实现将日期转换成timestamp

OUTLINE 常见的时间字符串与timestamp之间的转换 日期与timestamp之间的转换 常见的时间字符串与timestamp之间的转换 这里说的字符串不是一般意义上的字符串,...

Python发送邮件功能示例【使用QQ邮箱】

Python发送邮件功能示例【使用QQ邮箱】

本文实例讲述了Python发送邮件功能。分享给大家供大家参考,具体如下: 这里以QQ邮箱为例说明 登录邮箱点账号 开启smtp 开启时会要求你发送一条短信,发送完成后点已发送。 就有...