[英]Trying to rotate a matrix 90 degrees but fails to work
def rotate_ninety(matrix):
putin = []
temporary = []
row_size = len(matrix)
col_size = len(matrix[0])
ccount = col_size-1
putin_idx = 0
while ccount > -1:
for i in range(row_size):
temporary.insert(i, matrix[i][ccount])
putin.insert(putin_idx, temporary)
ccount = ccount -1
temporary.clear()
putin_idx += 1
print(putin)
return 0
So, if I had the input所以,如果我有输入
[1,2,3]
[4,5,6]
[7,8,9]
The result should be:结果应该是:
[3,6,9]
[2,5,8]
[1,4,7]
However, when I print putin I get [[] [] []], an array of all empty things, which I don't understand where my logic went wrong.但是,当我打印 putin 时,我得到 [[] [] []],一个全是空的数组,我不明白我的逻辑哪里出了问题。 I know there are other more efficient ways to do this, but I don't see how my code is wrong
我知道还有其他更有效的方法可以做到这一点,但我看不出我的代码有什么问题
When you assign (append or insert) a list
to a variable (another list), the list object
will be assigned or appended.当您将
list
分配(追加或插入)到变量(另一个列表)时,将分配或追加list object
。 Since after you add the temporary
list to the putin
list and then clearing the temporary
, the object that has been added just got removed,too.因为在将
temporary
列表添加到putin
列表然后清除temporary
列表之后,已添加的 object 也被删除了。 You need to add a copy
of the temporary
list to the putin
, like this:您需要将
temporary
列表的copy
添加到putin
,如下所示:
import copy
def rotate_ninety(matrix):
putin = []
temporary = []
row_size = len(matrix)
col_size = len(matrix[0])
ccount = col_size-1
putin_idx = 0
while ccount > -1:
for i in range(row_size):
temporary.append(matrix[i][ccount])
putin.append(copy.copy(temporary))
ccount = ccount -1
temporary.clear()
putin_idx += 1
print(putin)
return 0
matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate_ninety(matrix)
And the result will be:结果将是:
[[3, 6, 9], [2, 5, 8], [1, 4, 7]]
Here's a simply way with numpy:这是 numpy 的简单方法:
matrix = np.arange(1,10).reshape((3,3))
rotated_90 = matrix.T[::-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.