Python:为什么这个列表列表包含引用而不是副本?
Python: Why does this list of lists contains references instead of copies?
我有以下 python2 程序:
A=[]
for i in range(2):
A.append(list(["hello"]))
print "A is",A
F=[]
for i in range(2):
F.append(list(A))
print "F[0] is", F[0]
print "F[1] is", F[1]
F[0][0].append("goodbye")
print "F[0][0] is", F[0][0]
print "F[1][0] is", F[1][0]
当我 运行 它时,我得到输出:
A is [['hello'], ['hello']]
F[0] is [['hello'], ['hello']]
F[1] is [['hello'], ['hello']]
F[0][0] is ['hello', 'goodbye']
F[1][0] is ['hello', 'goodbye']
我原以为 F[1][0]
的内容只是 ['hello']
。我认为如果我写了程序的当前行为将是正常的
F.append(A)
而不是 F.append(list(A))
。但是,通过写 list(A)
而不仅仅是 A
我应该按值而不是按引用传递列表 A
。
我在这里误解了什么?
编辑:如果我写 F.append(A[:])
而不是 F.append(list(A))
,程序会有相同的行为
list(a) 和 a[:] 对可变对象的集合有限制,因为内部对象保持它们的引用不变。
在这种情况下,您应该使用 deepcopy
。
特别是应该F.append(copy.deepcopy(A))
而不是F.append(list(A))
。
我有以下 python2 程序:
A=[]
for i in range(2):
A.append(list(["hello"]))
print "A is",A
F=[]
for i in range(2):
F.append(list(A))
print "F[0] is", F[0]
print "F[1] is", F[1]
F[0][0].append("goodbye")
print "F[0][0] is", F[0][0]
print "F[1][0] is", F[1][0]
当我 运行 它时,我得到输出:
A is [['hello'], ['hello']]
F[0] is [['hello'], ['hello']]
F[1] is [['hello'], ['hello']]
F[0][0] is ['hello', 'goodbye']
F[1][0] is ['hello', 'goodbye']
我原以为 F[1][0]
的内容只是 ['hello']
。我认为如果我写了程序的当前行为将是正常的
F.append(A)
而不是 F.append(list(A))
。但是,通过写 list(A)
而不仅仅是 A
我应该按值而不是按引用传递列表 A
。
我在这里误解了什么?
编辑:如果我写 F.append(A[:])
而不是 F.append(list(A))
list(a) 和 a[:] 对可变对象的集合有限制,因为内部对象保持它们的引用不变。
在这种情况下,您应该使用 deepcopy
。
特别是应该F.append(copy.deepcopy(A))
而不是F.append(list(A))
。