一组顺时针转圈的数字,怎么按照顺时针的顺序输出??

[
[1 , 2, 3, 4, 5, 6],
[22,23,24,25,26, 7],
[21,36,37,38,27, 8],
[20,35,42,39,28, 9],
[19,34,41,40,29,10],
[18,33,32,31,30,11],
[17,16,15,14,13,12],
]
这么一个数组
按顺时针的顺序输出到1-42
用for if
要设计成可变的
现在时6*7 改成6*6 也是可以正确顺序输出的

以前写过一个狠暴力的代码,收下吧,记得采纳:

def write_res(arr):
    h=len(arr)
    w=len(arr[0])
    locx=0
    locy=0
    res=[arr[0][0]]
    arr[0][0]="a"
    while len(res)<w*h:
        while locx+1<w and arr[locy][locx+1]!="a":
            locx+=1
            res.append(arr[locy][locx])
            arr[locy][locx]="a"
        while locy+1<h and arr[locy+1][locx]!="a":
            locy+=1
            res.append(arr[locy][locx])
            arr[locy][locx]="a"
        while locx-1>=0 and arr[locy][locx-1]!="a":
            locx-=1
            res.append(arr[locy][locx])
            arr[locy][locx]="a"
        while locy-1<w and arr[locy-1][locx]!="a":
            locy-=1
            res.append(arr[locy][locx])
            arr[locy][locx]="a"

    print(res)

a=[
[1 , 2, 3, 4, 5, 6],
[22,23,24,25,26, 7],
[21,36,37,38,27, 8],
[20,35,42,39,28, 9],
[19,34,41,40,29,10],
[18,33,32,31,30,11],
[17,16,15,14,13,12],
]
write_res(a)         

抱歉,没有认真读题,要用for,改了一下:

def write_res2(arr):
    h=len(arr)
    w=len(arr[0])
    locx=0
    locy=0
    res=[arr[0][0]]
    arr[0][0]="a"
    for _ in range(min(int((h+1)/2),int((w+1)/2))):
        for _ in range(w): 
            if locx+1<w and arr[locy][locx+1]!="a":
                locx+=1
                res.append(arr[locy][locx])
                arr[locy][locx]="a"
            else:
                break
        for _ in range(h):
            if locy+1<h and arr[locy+1][locx]!="a":
                locy+=1
                res.append(arr[locy][locx])
                arr[locy][locx]="a"
            else:
                break
        for _ in range(w):
            if locx-1>=0 and arr[locy][locx-1]!="a":
                locx-=1
                res.append(arr[locy][locx])
                arr[locy][locx]="a"
            else:
                break
        for _ in range(h):
            if locy-1<w and arr[locy-1][locx]!="a":
                locy-=1
                res.append(arr[locy][locx])
                arr[locy][locx]="a"
            else:
                break

    print(res)

a=[
[1 , 2, 3, 4, 5, 6],
[18,19,20,21,22, 7],
[17,28,29,30,23, 8],
[16,27,26,25,24, 9],
[15,14,13,12,11,10]
]
write_res2(a)