我有一个转置方阵的程序:
matrix = [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
matrix _trans = []
for i in range (len (matrix)):
for j in range (len (matrix)):
matrix_trans [j] [i] = matrix [i] [j]
错误:
IndexError: list index out of range
为什么在此产生此错误?
答案 0 :(得分:1)
问题在于matrix_trans
是一个空列表,这就是为什么您不能访问任何indx而是建立matrix
的副本的原因:
matrix = [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
matrix_trans = [x[:] for x in matrix]
答案 1 :(得分:1)
发生这种情况是由于matrix_trans[j][i]
,在第一次迭代中,j
和i
都将为零,而matrix_trans
是一个空列表,因此matrix_trans[0]
将引发索引错误,您应该在策略中拥有第一个矩阵尺寸的副本,如下所示:
from copy import deepcopy
matrix = [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
matrix_trans = deepcopy(matrix)
for i in range(len(matrix)):
for j in range(len(matrix)):
matrix_trans[j][i] = matrix[i][j]
结果:
In [41]: matrix_trans
Out[41]: [[1, 3, 6], [2, 6, 8], [4, 9, 2]]
In [42]: matrix
Out[42]: [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
有关copy
模块的更多信息,请阅读Docs
此外,请注意,对于此操作,您可以使用Python zip
。像这样:
list(zip(*matrix))