本篇主要介绍了对一个N*N的数组,如果进行90度的旋转
首先,定义一个一维数组很简单,如下:
a = [i for i in range(10)] print(a) -----结果----- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
此写法与下面的写法是相同的效果:
a = [] for i in range(10): a.append(i) print(a) -----结果----- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
那么二维数组应该如何进行创建呢,如下:
a = [[col for col in range(4)] for row in range(4)] #创建一个4*4的二维数组 print(a) -----结果---- [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
如果想要直观一些,稍微调整下:
a = [[col for col in range(4)] for row in range(4)] for i in a: print(i) -----结果----- [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3]
接下来我们就要针对这个数组进行90度的旋转,把
[0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3] [0, 1, 2, 3]
转换为:
[0, 0, 0, 0] [1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3]
要实现该功能,我们先把步骤拆为3步:
第一步:
第二步:
第三步:
代码如下:
data = [[col for col in range(4)] for row in range(4)] for row_index, row in enumerate(data): for col_index in range(row_index, len(row)): tmp = data[col_index][row_index] #设置一个临时变量 data[col_index][row_index] = row[col_index] data[row_index][col_index] = tmp print(‘‘) #防止打印结果看上去混乱,输入一个空内容 for r in data: #分步骤打印出转换结果 print(r) -----结果----- [0, 0, 0, 0] [1, 1, 2, 3] [2, 1, 2, 3] [3, 1, 2, 3] [0, 0, 0, 0] [1, 1, 1, 1] [2, 2, 2, 3] [3, 3, 2, 3] [0, 0, 0, 0] [1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3] [0, 0, 0, 0] [1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3]