difference between adding lists in python with + and +=
我在用列表进行试验时注意到,
1 2 3 4 5 | test = [0, 1, 2, 3,] p = test test1 = [8] p = p + test1 print test |
在上述代码中,
但如果我用
1 2 3 4 5 6 7 | test = [0, 1, 2, 3,] p = test test1 = [8] p += test1 print test |
不同价值的原因是什么?
来自http://docs.python.org/2/reference/datamodel.html object.iadd:方法iadd(self,other)等
These methods are called to implement the augmented arithmetic
assignments (+=, -=, =, /=, //=, %=, *=, <<=, >>=, &=, ^=, |=).
These methods should attempt to do the operation in-place (modifying
self) and return the result
托比亚斯·库克已经解释过了。
简而言之,使用+而不是+=直接更改对象,而不是指向对象的引用。
从上面链接的答案中引用:
When doing foo += something you're modifying the list foo in place,
thus you don't change the reference that the name foo points to, but
you're changing the list object directly. With foo = foo + something,
you're actually creating a new list.
以下是发生这种情况的示例:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> alist = [1,2] >>> id(alist) 4498187832 >>> alist.append(3) >>> id(alist) 4498187832 >>> alist += [4] >>> id(alist) 4498187832 >>> alist = alist + [5] >>> id(alist) 4498295984 |
在您的例子中,测试被更改,因为p是对测试的引用。
1 2 3 4 5 6 | >>> test = [1,2,3,4,] >>> p = test >>> id(test) 4498187832 >>> id(p) 4498187832 |