|
发表于 2022-11-26 21:00:23
|
显示全部楼层
还没看答案,切片研究了一下午,感觉这是比较笨的办法了
matrix = [[1, 2, 3, 4, 11,22],
[5, 6, 7, 8, 11,22],
[9, 10,11,12,11,22],
[13,14,15,16,11,22],
[17,18,19,20,11,22],
[21,22,23,24,11,22],
[25,26,27,28,29,30]]
longth = len(matrix)
longth1 = len(matrix[0])
longth2=longth*longth1
count = longth//2#因为是旋转的,所以列表总长度的一半就可以遍历完
top =0
low =0
left =0
right =0
tmatrix = []
#for循环内的print目的在于检测并发现问题,并无其他作用
while count>0:
for tfr in matrix[top][left:longth1]:#在第top行添加从left到longth1的元素
print(tfr,'A')
tmatrix.append(tfr)
for rtl in matrix[right+1:longth]:#遍历rigth+1列到longth列的列表
print(rtl[(-1-right)],'B')#只添加rtl[-1-right]位置的元素
tmatrix.append(rtl[(-1-right)])
for lrl in matrix[longth-1][longth1-2:(-longth1-1):-1]:#在longth-1行,
#倒叙添加longth1-2到(-longth1-1)中的元素
print(lrl ,'C')
tmatrix.append(lrl)
for llt in reversed(matrix[(left+1):(longth-1)]):#先翻转外层列表
#然后遍历(left+1)列到(longth-1)列的列表
print(llt[left],'D') #只添加llt[left]位置的元素
tmatrix.append(llt[left])
if len(tmatrix)>= longth2:#如果新列表数量等于二维列表长度,跳出循环
break
top+=1
low-=1
left+=1
right+=1
longth-=1
longth1-=1
count-=1
print(tmatrix) |
|