python 顺时针打印矩阵的超简洁代码

yipeiwu_com5年前Python基础

如下所示:

# -*- coding:utf-8 -*-
class Solution:
  # matrix类型为二维列表,需要返回列表
  def printMatrix(self, matrix):
    # write code here
    res=[]
    n=len(matrix)
    m=len(matrix[0])
    if m==1 and n==1:
      res=[matrix[0][0]]
      return res
    else:
      for o in range((min(m,n)+1)//2):
        [res.append(matrix[o][i]) for i in range(o,m-o)]
        [res.append(matrix[j][m-o-1]) for j in range(o,n-o) if matrix[j][m-o-1] not in res]
        [res.append(matrix[n-o-1][k]) for k in range(m-1-o,o-1,-1) if matrix[n-o-1][k] not in res]
        [res.append(matrix[l][o]) for l in range(n-1-o,o-1,-1) if matrix[l][o] not in res]
      return res

以上这篇python 顺时针打印矩阵的超简洁代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现对文件中图片生成带标签的txt文件方法

在深度学习中经常需要生成带标签的图片名称列表,xxxlist.txt文件,下面写一个简单的python脚本生成该文件列表。 import os def generate(dir,la...

python计算时间差的方法

本文实例讲述了python计算时间差的方法。分享给大家供大家参考。具体分析如下: 1、问题: 给定你两个日期,如何计算这两个日期之间间隔几天,几个星期,几个月,几年? 2、解决方法: 标...

python读取ini配置的类封装代码实例

这篇文章主要介绍了python读取ini配置的类封装代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 此为基础封装,未考虑过多异...

pyqt5 QScrollArea设置在自定义侧(任何位置)

pyqt5 QScrollArea设置在自定义侧(任何位置)

本例设置为垂直左侧scroll 主要思想是利用一个长度为0的mid_frame,高度为待设置qwidget的高度,用mid_frame的moveEvent事件驱动qwidget的move...

详解python while 函数及while和for的区别

详解python while 函数及while和for的区别

1.while循环(只有在条件表达式成立的时候才会进入while循环) while 条件表达式:   pass while 条件表达式:   pass else:   pass 不知道...