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使用multiprocessing实现一个最简单的分布式作业调度系统

 mutilprocess像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多。 介绍 P...

python re正则匹配网页中图片url地址的方法

python re正则匹配网页中图片url地址的方法

最近写了个python抓取必应搜索首页http://cn.bing.com/的背景图片并将此图片更换为我的电脑桌面的程序,在正则匹配图片url时遇到了匹配失败问题。 要抓取的图片地址如图...

flask框架自定义过滤器示例【markdown文件读取和展示功能】

本文实例讲述了flask框架自定义过滤器。分享给大家供大家参考,具体如下: 除了一些内置的join length safe等过滤器外, flask还提供了自定义过滤器的功能. 一. 自定...

解决python replace函数替换无效问题

python replace函数替换无效问题 str = "hello,china!" str.replace("hell","well") print(str) hello,C...

TensorFlow实现简单卷积神经网络

TensorFlow实现简单卷积神经网络

本文使用的数据集是MNIST,主要使用两个卷积层加一个全连接层构建的卷积神经网络。 先载入MNIST数据集(手写数字识别集),并创建默认的Interactive Session(在没有指...