gpt4 book ai didi

Python 转置矩阵给我错误的 python

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:43 24 4
gpt4 key购买 nike

然而,我写了一个转置矩阵函数,当我尝试运行它时,输出中的值最终变得相同。附件是输出的图片。我的代码也有评论。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com