reversed与zip的用法:顺时针方向读取二维数组


之前的博文中谈到了 python3 zip的用法 ,现在看看reversed与zip配合,顺时针读取二维数组的方法。

例题

注:例题来自 https://www.codewars.com/kata/snail/python

  1. 给定一个n*n的矩阵,通过函数 snail()得到按顺时针方向读取的list:
    array = [[1,2,3],
    [4,5,6],
    [7,8,9]]
    snail(array) #=> [1,2,3,6,9,8,7,4,5]
    即:
    [[1–>2–>3],
    [4–>5      6],
    [7<–8<–9]]
  2. 如果给定的矩阵为0*0,返回[[]]

解法

def snail(array):
    #1. Pop top row
    #2. Transpose and flip upside-down (same as rotate 90 degrees counter-clockwise)
    #3. Go to 1
    #and reference:
    #http://stackoverflow.com/questions/1655685/traverse-2d-array-in-spiral-pattern-using-recursion

    return list(array[0]) + snail(list(reversed(list(zip(*array[1:]))))) if array else []

解题思路是:
1. 先取到矩阵的第一行元素
2. 将去除了第一行元素的矩阵逆时针旋转90度:zip方法或transpose方法进行行列转换之后,再使用reverse方法将矩阵上下倒置
3. 回到第一步

reverse方法

python doc:

reversed(seq)
Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).

例如:

list(reversed([‘dream’,’a’,’have’,’I’]))
>>>[‘I’, ‘have’, ‘a’, ‘dream’]

需要注意的是: reverse()方法会改变操作对象,如

>>> a = [1,2,3,4]
>>> b = a
>>> b
[1, 2, 3, 4]
>>> b.reverse()
>>> b
[4, 3, 2, 1]
>>> a
[4, 3, 2, 1]

而reversed()不会,如:

>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> b = a
>>> b
[1, 2, 3, 4]
>>> reversed(b)

>>> list(reversed(b))
[4, 3, 2, 1]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]


参考
http://stackoverflow.com/questions/1655685/traverse-2d-array-in-spiral-pattern-using-recursion

http://stackoverflow.com/questions/726756/print-two-dimensional-array-in-spiral-order

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值