What was the motivation for doing lists augmented assignment (+=) in place in python?
1 2 3 4 5 | >>> list1 = [] >>> list2 = list1 >>> list2 += [1] >>> print list1 [1] |
将此与
1 2 3 4 5 | >>> list1 = [] >>> list2 = list1 >>> list2 = list2 + [1] >>> print list1 [] |
"+="-操作修改原始列表是否有原因?
编辑:只是想让我的问题更清楚一点
在我所知道的大多数语言中,'+='-操作符都不是这样工作的,我想知道为什么它在Python中是这样设计的。
一些例子:
红宝石
1 2 3 4 5 | irb(main):001:0> l = [] irb(main):002:0> a = l irb(main):003:0> a += [2] irb(main):004:0> l => [] |
斯卡拉等。
以引用方式存储在python中的列表。
这意味着当你做
python将
因此,当您附加到
然而,对于
因此,当您执行
在python 2.6.4文档的第6.2.1节中。(扩充的赋值语句)
An augmented assignment expression like
x += 1 can be rewritten asx = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.
[添加强调]
请参阅有关模拟数字类型的文档,该文档描述了实现此行为的方法。这也适用于列表:
These methods are called to implement the augmented arithmetic assignments (
+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |= ). These methods should attempt to do the operation in-place (modifyingself ) and return the result (which could be, but does not have to be,self ). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statementx += y , wherex is an instance of a class that has an__iadd__() method,x.__iadd__(y) is called. Ifx is an instance of a class that does not define a__iadd__() method,x.__add__(y) andy.__radd__(x) are considered, as with the evaluation ofx + y .
当您执行
1 2 3 4 5 6 7 8 9 | >>> l = [] >>> id(l) 41523720L >>> l += [3] >>> id(l) 41523720L # same as l = [] >>> l = l+[3] >>> id(l) 41532232L |
这就解释了区别。
好吧,因为这就是它的工作原理。编写
在Python中,您所认为的变量名在大多数情况下更类似于指针;"="不复制对象,它将新名称绑定到该对象(在其他上下文中为"按引用复制")。因此,
可以按元素(
这就是
1 | a += b |
方法
1 | a = a + b |
但是你的特定场景有一个不同的问题。当你写作时
1 | list2 = list1 |
没有复制;
在您的第二个代码片段中,
(nitpicker's corner:使用运算符重载,可以构造一个对