首页 >

python顺时针遍历二维数组的实现方法 |linux如何调试python脚本

python list 中文,python创意,怎样进python,华为python面试难不,optiongroup python,ib python,python的TypeVar,python escpos windows,python文件文本,python搭建ssr,linux如何调试python脚本python顺时针遍历二维数组的实现方法 |linux如何调试python脚本

方法一模拟

这是一种比较暴力的方法,大家可以模拟人类读取二维数组的方法,从左到右,从上到下,从右到左,从下到上,以此类推,以下是代码实现

atrix)otatrix []

res = []atrixatrix[0]) = 0, cols – 1, 0, rows – 1dge(left, right + 1)datrix[top][col])ge + 1)datrix[row][right])dge(right – 1, left – 1, -1)datrix][col])ge – 1, top, -1)datrix[row][left]) – 1 res

方法二递归

递归是一种比较巧妙的方法,大家可以将整个二维数组看成由一层层的圈组成,然后每次递归遍历一圈,以下是代码实现

atrix)otatrix []atrixatrix[0])atrix.pop(0)

if rows >1ge(rows – 1)datrix[i].pop())

if cols >1atrix.pop()[-1]ge(rows – 2, 0, -1)datrix[i].pop(0))atrixgeatrixatrix[i]]) res

方法三迭代器

迭代器是一种比较简洁的方法,大家可以将整个二维数组看成由一层层的圈组成,然后每次遍历一圈,以下是代码实现

class SpiralIteratoritatrix)atrixatrix

self.row, self.col = 0, -1s = [(0, 1), (1, 0), (0, -1), (-1, 0)]

def __iter__(self) self

ext__(self)s

r, c = self.row + dr, self.col + dcatrixdatrixdatrixote

self.row, self.col = r, catrix[self.row][self.col]atrixe

atrix)otatrix []atrix))

以上是三种常用的方法来实现顺时针遍历二维数组。不同的方法各有优缺点,大家可以根据实际情况选择合适的方法。


python顺时针遍历二维数组的实现方法 |linux如何调试python脚本
  • python中换行的代码怎么写? |spark用python
  • python中换行的代码怎么写? |spark用python | python中换行的代码怎么写? |spark用python ...

    python顺时针遍历二维数组的实现方法 |linux如何调试python脚本
  • python获取某年数据(详解Python数据获取方法) |python 列表与字典
  • python获取某年数据(详解Python数据获取方法) |python 列表与字典 | python获取某年数据(详解Python数据获取方法) |python 列表与字典 ...

    python顺时针遍历二维数组的实现方法 |linux如何调试python脚本
  • Python3安装组件轻松掌握的10个适用方法 |python cs系统开发
  • Python3安装组件轻松掌握的10个适用方法 |python cs系统开发 | Python3安装组件轻松掌握的10个适用方法 |python cs系统开发 ...