我正在尝试编写一个矩阵(二维列表)转置函数,很有趣,在处理它时,我遇到了这种非常奇怪的行为。对我来说,以下功能几乎相同(除了另一个功能对生成的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
函数仍给出错误的结果?