【发布时间】:2022-01-10 20:09:24
【问题描述】:
我正在尝试编写一个 for 循环,该循环采用 2D 矩阵的内容并将它们旋转 90 度以进行写入,如下所示:
|2|3|4|5|
---------
|7|6|8|9|
to:
|7|2|
-----
|6|3|
-----
|8|4|
-----
|9|5|
my code so far is:
rotated = []
#you may change matrix as you want
matrix=[[1 , 2 , 3] ,[ 4 , 5 , 6]]
# append a new matrix for each col
for i in range(len(matrix[0])):
rotated.append([])
# append the last up till the 1st item to the 1st list in our new rotated list
for j in range(len(matrix) - 1, -1, -1):
rotated[i].append(matrix[j][i])
print(rotated)
【问题讨论】:
-
只要用
zip()list(zip(*reversed(l)))给你[(7, 2), (6, 3), (8, 4), (9, 5)] -
在最后一行...你应该使用旋转或定义旋转来使代码运行
标签: python for-loop multidimensional-array