问题描述
为什么这两个操作(append()
和+
)会给出不同的结果?
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?
推荐答案
解释为什么":
+
操作添加array 元素到原始数组.array.append
操作将数组(或任何对象)插入到原始数组的末尾,这会导致在该位置对 self 的引用(因此是无限递归).
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.
使用 extend()
如果您想使用类似于 + 运算符的功能(正如其他人在此处显示的那样).做相反的事情是不明智的:尝试用 + 运算符模拟列表的追加(请参阅我的 早期链接为什么).
为了好玩,有一点历史:诞生1993 年 2 月 Python 中的数组模块.它可能会让你感到惊讶,但数组是在序列和列表出现之后添加的.
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 append() 与列表上的 + 运算符,为什么这些会给出不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!