Python:顺时针方向的二维到一维列表?

标签 python list rotation

我是 Python 的新手,我正在寻找一个可以将任何 n x 转换为 n函数 n 二维列表到一维列表 顺时针方向

例如:

当 n = 3

list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]

list = [[2, 3, 5]
       ,[8, 7, 1]
       ,[0, 4, 6]]

会变成

result = [2, 3, 5, 1, 6, 4, 0, 8, 7]

当 n = 5

列表 = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17、18、25]、[14、15、16、23、24]]

list = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

会变成

result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]

对于 nxn 的任何值,我怎样才能有效地做到这一点?

最佳答案

改编自Print two-dimensional array in spiral order

import itertools

arr = [[2,  3,  5,  9, 10],
       [8,  7,  1, 11, 13],
       [0,  4,  6, 21, 22],
       [12, 19, 17, 18, 25],
       [14, 15, 16, 23, 24]]


def transpose_and_yield_top(arr):
    while arr:
        yield arr[0]
        arr = list(zip(*arr[1:]))[::-1]


rotated = list(itertools.chain(*transpose_and_yield_top(arr)))

关于Python:顺时针方向的二维到一维列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44412098/

相关文章:

python - MongoDB Atlas 中新集群的默认密码

python - 将列表的列表转换为对象

python - 如何将数据保存到文件而不是字典列表

javascript - 围绕世界轴旋转对象

ios - viewWillTransitionToSize : vs willTransitionToTraitCollection:

c++ - 在 OpenCV 中使用旋转和平移矩阵

python - 在Python中的函数中连接任意数量的列表

python - 添加带有多个小部件链接的右键单击上下文菜单?

python - 如何简单地用python处理请求

python-3.x - 收集特殊键和值并将其放在字典中