我编写了一个转置矩阵函数,但是,当我尝试运行它时,输出中的值最终变得相同。附上一张输出图片。我的代码也被注释了。
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 等。 output
最佳答案
此行为有更全面的解释 here ,所以我建议你看一下。
当您使用行 temp_matrix += [temp_row]
时,您将列表对象 temp_row
添加到数组中(在本例中为三次。)
当你说
temp_matrix[c][r] = value
该值在 temp_row
对象中被覆盖,因为 temp_matrix[c]
与是同一对象temp_row
,因此当您打印整个 temp_matrix 时,它会打印出它是什么:对同一矩阵的 3 个引用。
使用 list.copy()
方法应该通过添加一个新的 list
对象(即 temp_row
)到temp_matrix
。
这是一些工作代码:
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] ]
关于Python 转置矩阵 给我错误的 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52544456/