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

yipeiwu_com7年前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使用PIL模块生成随机验证码

Python生成随机验证码,需要使用PIL模块,具体内容如下 安装: pip3 install pillow 基本使用 1. 创建图片 from PIL import Ima...

python 如何将数据写入本地txt文本文件的实现方法

一、读写txt文件 1、打开txt文件 file_handle=open('1.txt',mode='w') 上述函数参数有(1.文件名,mode模式) mode模式有以下几种...

Python内置的字符串处理函数详细整理(覆盖日常所用)

str='python String function' 生成字符串变量str='python String function' 字符串长度获取:len(str) 例:print '%s...

Django框架之DRF 基于mixins来封装的视图详解

基础视图 示例环境搭建:新建一个Django项目,连接Mysql数据库,配置路由、视图函数、序列化单独创建py文件 # 配置路由 from django.conf.urls imp...

举例讲解Python面相对象编程中对象的属性与类的方法

python 对象的属性 进入正题,来看一个实例来了解python中类,对象中公有属性,私有属性及局部变量,全局变量的区别. root@10.1.6.200:~# cat objec...