用+和+ =在python中添加列表之间的区别 [英] difference between adding lists in python with + and +=
问题描述
在尝试使用列表时,我注意到p= p+i
与p += i
不同
例如:
I've noticed when experimenting with lists that p= p+i
is different then p += i
For example:
test = [0, 1, 2, 3,]
p = test
test1 = [8]
p = p + test1
print test
在上面的代码中,test
打印为[0, 1, 2, 3,]
In the above code test
prints out to the original value of [0, 1, 2, 3,]
但是,如果我用p += test1
切换p = p + test1
,如下所示:
But if I switch p = p + test1
with p += test1
As in the following
test = [0, 1, 2, 3,]
p = test
test1 = [8]
p += test1
print test
test
现在等于[0, 1, 2, 3, 8]
值不同的原因是什么?
推荐答案
p = p + test1
为变量p
分配新值,而p += test1
扩展存储在变量p
中的列表.而且,由于p
中的列表与test
中的列表相同,因此追加到p
也会追加到test
,尽管将新值分配给变量p
不会更改分配给test
的值>以任何方式.
p = p + test1
assigns a new value to variable p
, while p += test1
extends the list stored in variable p
. And since the list in p
is the same list as in test
, appending to p
also appends to test
, while assigning a new value to the variable p
does not change the value assigned to test
in any way.
这篇关于用+和+ =在python中添加列表之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!