python将⼆维数组旋转_python-⼆维数组实现90度旋转本篇主要介绍了对⼀个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:
python 定义数组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]
转换为:
[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]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论