【发布时间】:2015-04-07 23:09:25
【问题描述】:
我有以下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)),程序具有相同的行为
【问题讨论】:
标签: python list reference pass-by-reference