Python:为什么这个列表包含引用而不是副本?

2024-04-25 03:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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)),程序也有相同的行为


Tags: in程序编辑内容hello列表foris
1条回答
网友
1楼 · 发布于 2024-04-25 03:33:23

列表(a)和a[:]对可变对象的集合有限制,因为内部对象保持其引用完好无损。 在这种情况下,应该使用^{}。你知道吗

特别是,它应该是F.append(copy.deepcopy(A)),而不是F.append(list(A))。你知道吗

相关问题 更多 >