我是 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/