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
    #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/

相关文章:

python - 530 使用 ftplib 进行身份验证时出错

python - 扭曲的Python+spawnProcess。从命令获取输出

bool 函数的 Python 模拟

python - pandas如何计算偏斜

python - 摄影(或匹配两张照片)

python - 在 Python 3.6.10 上运行异步 Flask 2.0.0 时出错

python - 使用 rpy2 更改 ggplot2 中的图例

python - Numpy 掩码数组 - 指示缺失值

python - 如何将动态pyplot保存为电影文件?

python - 我该如何用 Python 3.3.2 编写这个程序?