Python转置矩阵给了我错误的Python
然而,我编写了一个转置矩阵函数,当我尝试运行它时,输出中的值最终变得相同。附件是输出的图片。我的代码也被注释了Python转置矩阵给了我错误的Python,python,Python,然而,我编写了一个转置矩阵函数,当我尝试运行它时,输出中的值最终变得相同。附件是输出的图片。我的代码也被注释了 def transpose(any_matrix): _row = len(any_matrix) _col = len(any_matrix[0]) temp_matrix = [] #multiplies [0] by the number of rows (old) to create new row temp_row = [0]*_row
def transpose(any_matrix):
_row = len(any_matrix)
_col = len(any_matrix[0])
temp_matrix = []
#multiplies [0] by the number of rows (old) to create new row
temp_row = [0]*_row
#creates matrix with number of columns as rows
for x in range(_col):
temp_matrix += [temp_row]
for r in range(len(any_matrix)):
for c in range(len(any_matrix[0])):
value = any_matrix[r][c]
temp_matrix[c][r] = value
return temp_matrix
a = [[4, 5, 6], [7,8,9]]
print(transpose(a))
#input [[4,5,6]
# [7,8,9]]
#correct answer [ [4,7],
# [5,8],
# [6,9] ]
我不喜欢使用其他库,如numpy等。
对这种行为有了更全面的解释,因此我建议您看看 当您使用行
temp\u matrix+=[temp\u row]
时,您将列表对象temp\u row
添加到数组中(在本例中为三次)
当你说
temp_matrix[c][r] = value
该值在temp_行
对象中被覆盖,因为temp_矩阵[c]
与temp_行
是同一对象,所以当您打印整个temp_矩阵时,它会打印出它是什么:对同一矩阵的3个引用
使用list.copy()
方法应该通过向temp\u矩阵添加一个新的list
对象(即temp\u行的副本)来绕过这个不需要的有效指针。
下面是一些工作代码:
def transpose(any_matrix):
_row = len(any_matrix)
_col = len(any_matrix[0])
temp_matrix = []
#multiplies [0] by the number of rows (old) to create new row
temp_row = [0]*_row
#creates matrix with number of columns as rows
for x in range(_col):
temp_matrix += [temp_row.copy()]
for r in range(len(any_matrix)):
for c in range(len(any_matrix[0])):
value = any_matrix[r][c]
temp_matrix[c][r] = value
return temp_matrix
a = [[4, 5, 6], [7,8,9]]
print(transpose(a))
#input [[4,5,6]
# [7,8,9]]
#correct answer [ [4,7],
# [5,8],
# [6,9] ]
我没有得到相同的输出:[[6,9],[6,9],[6,9]]
仍在寻找答案,请参见。temp_矩阵的行都是相同的temp_行
list。转换列表矩形列表的惯用方法,例如,a=[list(range(n,n*6,n))表示范围(1,12)中的n]
是a_transpose=[list(col)表示zip中的col(*a)]
OP还可以将temp_矩阵实例化为一个由零组成的矩阵,这样可以解决问题。这是真的。我也想试着解释一下这种行为。非常感谢你。我已经有一段时间对这种行为发疯了。我记得我第一次遇到这种情况的时候。字典里也有。当心。