用+和+ =在python中添加列表之间的区别 [英] difference between adding lists in python with + and +=

查看:101
本文介绍了用+和+ =在python中添加列表之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用列表时,我注意到p= p+ip += 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆