问题描述
为什么这两个操作(追加()
RESP。 +
)给出不同的结果?
Why do these two operations (append()
resp. +
) give different results?
>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>>
在过去的情况下,有实际上是一个无限递归。 C [-1]
和 C
是相同的。为什么与 +
的操作有什么不同?
In the last case there's actually an infinite recursion. c[-1]
and c
are the same. Why is it different with the +
operation?
推荐答案
+
操作增加 元素原始数组。在<一个href=\"http://docs.python.org/library/array.html?highlight=append#array.array.append\"><$c$c>array.append$c$c>操作插入阵列(或任何物体)到原始数组的末尾,这导致的参考在该点自的(因此无限递归)。
To explain "why":
The +
operation adds the array elements to the original array. The array.append
operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).
这里的区别是,当你添加阵列(它的超载其他人一样,看到的的序列)通过连接的元素。然而,追加法从字面上做什么你问:追加对你给它(数组或任何其他对象),右手边的对象,而不是采取它的元素
The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.
使用<一个href=\"http://docs.python.org/library/array.html?highlight=append#array.array.extend\"><$c$c>extend()$c$c>如果你想使用作用类似于+运算功能(如其他人在这里显示为好)。这不是明智的做法是反其道而行之:要尽量模仿与+运营商名单追加(见我的)。
为了好玩,一点点的历史:在Python阵列模块的在1993年2月它可能会让你大吃一惊,但阵列中添加方式后的序列,并列出应运而生。
For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.
这篇关于Python的追加()与+操作的列表,为什么这些给出不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!