本文介绍了LIST.append(1) 和 LIST = LIST + [1] (Python) 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行(我使用交互式 shell)这些语句时,我得到了这个:

L=[1,2,3]K=LL.append(4)升[1,2,3,4]钾[1,2,3,4]

但是当我用 L=L+[4] 替换 L.append(4) 做同样的事情时我得到:

L[1,2,3,4]钾[1,2,3]

这是某种参考吗?为什么会发生这种情况?

我注意到的另一件有趣的事情是 L+=[4] 的作用类似于 .append,这很奇怪,因为我认为它的作用类似于 L = L + [4].

对所有这些进行澄清将不胜感激.

谢谢

解决方案
L.append(4)

这会在现有列表L的末尾添加一个元素.

L += [4]

+= 运算符调用神奇的 __iadd__() 方法.结果证明 list 覆盖了 __iadd__() 方法并使其等效于 extend() ,类似于 append()code>,将元素直接添加到现有列表中.

L = L + [4]

L + [4] 生成一个新列表,它等于 L 的末尾添加 4.这个列表然后被分配回L.因为你已经创建了一个新的列表对象,K 不会被这个赋值改变.

我们可以使用 id() 来识别何时创建了新的对象引用:

>>>L = [1, 2, 3]>>>编号(L)152678284>>>L.append(4)>>>编号(L)152678284>>>L = [1, 2, 3]>>>编号(L)152680524>>>L = L + [4]>>>编号(L)152678316

When I execute (I'm using the interactive shell) these statements I get this:

L=[1,2,3]
K=L

L.append(4)

L
[1,2,3,4]
K
[1,2,3,4]

But when I do exactly the same thing replacing L.append(4) with L=L+[4]I get:

L
[1,2,3,4]
K
[1,2,3]

Is this some sort of reference thing? Why does this happen?

Another funny thing I noticed is that L+=[4] acts like .append, which is odd as I thought it would act like L = L + [4].

Clarification to all of this would be greatly appreciated.

Thanks

解决方案
L.append(4)

This adds an element on to the end of the existing list L.

L += [4]

The += operator invokes the magic __iadd__() method. It turns out list overrides the __iadd__() method and makes it equivalent to extend() which, like append(), adds elements directly onto an existing list.

L = L + [4]

L + [4] generates a new list which is equal to L with 4 added to the end. This new list is then assigned back to L. Because you've created a new list object, K is unchanged by this assignment.

We can use id() to identify when a new object reference is created:

>>> L = [1, 2, 3]
>>> id(L)
152678284
>>> L.append(4)
>>> id(L)
152678284

>>> L = [1, 2, 3]
>>> id(L)
152680524
>>> L = L + [4]
>>> id(L)
152678316

这篇关于LIST.append(1) 和 LIST = LIST + [1] (Python) 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:19