l1是一个列表,l2 = l1;为什么不"l2 = l2 + [item]"?影响"l1",而"l2 + = [item]"则影响l1.做? [英] l1 is a list, l2 = l1; why doesn't "l2 = l2 + [item]" affect l1 while "l2 += [item]" does?

查看:95
本文介绍了l1是一个列表,l2 = l1;为什么不"l2 = l2 + [item]"?影响"l1",而"l2 + = [item]"则影响l1.做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在Python中加等于(+ =)有什么作用?

Possible Duplicate:
What does plus equals (+=) do in Python?

我注意到一个奇怪的问题:

I noticed a strange problem:

    l1 = ['1', '2', '3']
    l2 = l1

    item = l2.pop(0)
    # the pop operation will effect l1
    print l1

    l2 = l2 + [item]
    # why "l2 = l2 + [item]" does't effect l1 while "l2 += [item]" does.
    print l2
    print l1

输出为:

['2', '3']
['2', '3', '1']
['2', '3']

但是如果我将l2 = l2 + [item]更改为l2 += [item],输出将是:

But if i change l2 = l2 + [item] into l2 += [item], the output will be:

['2', '3']
['2', '3', '1']
['2', '3', '1']

推荐答案

++=是不同的运算符,具有不同的内部含义,如

+ and += are different operators woth different internal meaning as described here.

l2 = l1 + x调用l2 = l1.__add__(x),如果不起作用,则调用x.__radd__(l1).两者都应返回一个独立于旧对象的新对象,以形成运算结果,从而不会影响l1.

l2 = l1 + x calls l2 = l1.__add__(x), if that doesn't work it calls x.__radd__(l1). Both should return a new object forming the result of the operation, independent from the old one, thus not affecting l1.

l2 += x调用l2 = l2.__iadd__(x)(扩展分配"),只有在这种方法不起作用的情况下,才会如上所述退回到l2 = l2 + x.

l2 += x calls l2 = l2.__iadd__(x) ("augmented assignment"), and only if this doesn't work, falls back to l2 = l2 + x as described above.

在数字上,两者是相同的,因为它们是不可变的,因此不能用+=修改.在列表上,+返回一个新对象,而+=修改左侧的对象.

With numbers, both are the same, because they are immutable and thus cannot be modified with +=, while on lists, + returns a new object while += modifies the left hand side one.

由于修改了l2后面的对象,并且l1引用了同一对象,因此您也会注意到l1上的更改.

As the object behind l2 is modified and l1 refers the same object, you notice the change on l1 as well.

这篇关于l1是一个列表,l2 = l1;为什么不"l2 = l2 + [item]"?影响"l1",而"l2 + = [item]"则影响l1.做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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