看似相同的代码会产生不同的结果?

时间:2019-04-20 22:20:02

标签: python python-3.x list nested-lists

我正在尝试编写一个矩阵(二维列表)转置函数,很有趣,在处理它时,我遇到了这种非常奇怪的行为。对我来说,以下功能几乎相同(除了另一个功能对生成的new列表的形式进行了硬编码)。

def transpose1(mat):
    new = [[None] * len(mat)] * len(mat[0])

    print("input1:", mat)
    print("new1:", new)

    for j, line in enumerate(mat):
        for i, elem in enumerate(line):
            new[i][j] = mat[j][i]

    return new


def transpose2(mat):
    # only line that differs, but still when
    # printing 'new' they seem identical
    new = [[None, None], [None, None], [None, None]]

    print("input2:", mat)
    print("new2:", new)

    for j, line in enumerate(mat):
        for i, elem in enumerate(line):
            new[i][j] = mat[j][i]

    return new


mat = [[4, 5, 6], [7, 8, 9]]

print("result1:", transpose1(mat))
print()
print("result2:", transpose2(mat))
  

输出:

input1: [[4, 5, 6], [7, 8, 9]]
new1: [[None, None], [None, None], [None, None]]
result1: [[6, 9], [6, 9], [6, 9]]

input2: [[4, 5, 6], [7, 8, 9]]
new2: [[None, None], [None, None], [None, None]]
result2: [[4, 7], [5, 8], [6, 9]]

我只是不了解new列表的声明对输出有什么不同。即使中间的transpose1列表在两种情况下看起来都相同且其余代码相同,为什么new函数仍给出错误的结果?

0 个答案:

没有答案