问题描述
为什么这两个操作(append()
和 +
)给出不同的结果?
在最后一种情况下,实际上是无限递归.c[-1]
和 c
是一样的.为什么和+
操作不一样?
解释为什么":
+
操作添加了array 元素到原始数组.array.append
操作将数组(或任何对象)插入到原始数组的末尾,这导致在那个位置引用 self(因此是无限递归).
这里的区别在于 + 操作在添加数组时是特定的(它像其他人一样重载,请参阅 本章关于序列)通过连接元素.然而,append 方法确实按照您的要求执行:将对象(数组或任何其他对象)添加到右侧,而不是获取其元素.
另一种选择
使用 extend()
如果你想使用一个类似于 + 操作符的函数(正如其他人在这里展示的那样).做相反的事情是不明智的:尝试用 + 运算符模拟列表的追加(请参阅我的 较早的链接 原因).
小历史
为了好玩,一点历史:诞生1993 年 2 月 Python 中的数组模块.你可能会感到惊讶,但数组是在序列和列表出现之后添加的.
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, [...]]
>>>
In the last case there's actually an infinite recursion. c[-1]
and c
are the same. Why is it different with the +
operation?
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.
An alternative
Use extend()
if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).
Little history
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() 与 + 运算符,为什么这些会给出不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!