清单上的Python append()与+运算符,为什么它们给出不同的结果?

问题:清单上的Python append()与+运算符,为什么它们给出不同的结果?

为什么这两个操作(append()分别+)给出不同的结果?

>>> 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一样。为什么与+操作不同?

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?


回答 0

解释“为什么”:

+操作数组元素添加到原始数组。该array.append操作将数组(或任何对象)插入到原始数组的末尾,从而导致对该点的self引用(因此无限递归)。

此处的区别在于,通过连接元素添加数组时,+操作是特定的(它像其他数组一样重载,请参见本章中的序列)。但是,append-method确实可以按照您的要求执行:将对象附加在您赋予它的右侧(数组或任何其他对象),而不是获取其元素。

替代

使用extend(),如果你想使用的作用类似于+运算符的功能(如其他人在这里显示为好)。相反,这样做是不明智的:尝试使用+运算符模仿列表的追加(有关原因,请参阅我之前的链接)。

小历史

有趣的是,有一段历史:1993年2月Python的数组模块诞生。这也许会让您感到惊讶,但是在序列和列表出现之后才添加了数组。

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.


回答 1

串联运算符+是一个二进制中缀运算符,当应用于列表时,它返回一个包含其两个操作数每个元素的所有元素的新列表。该list.append()方法是mutatoron list,将其单个object参数(在您的特定示例中为列表c)附加到主题list。在您的示例中,这导致c对其自身附加引用(因此可以进行无限递归)。

替代“ +”串联

list.extend()方法还是mutator方法,将其sequence参数与主题连接在一起list。具体来说,它sequence按迭代顺序附加的每个元素。

放在一边

作为运算符,+将表达式的结果作为新值返回。作为一种非链接mutator方法,list.extend()可就地修改主题列表,但不返回任何内容。

数组

我之所以添加此内容,是因为上述Abel的答案可能会由于混合列表,序列和数组的讨论而引起潜在的混乱。 Arrays是在序列和列表之后添加到Python的,这是一种更有效的方式来存储整数数据类型的数组。不要arrays与混淆lists。她们不一样。

数组文档

数组是序列类型,其行为与列表非常相似,不同之处在于数组中存储的对象类型受到约束。类型是在对象创建时通过使用类型代码(一个字符)指定的。

The concatenation operator + is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append() method is a mutator on list which appends its single object argument (in your specific example the list c) to the subject list. In your example this results in c appending a reference to itself (hence the infinite recursion).

An alternative to ‘+’ concatenation

The list.extend() method is also a mutator method which concatenates its sequence argument with the subject list. Specifically, it appends each of the elements of sequence in iteration order.

An aside

Being an operator, + returns the result of the expression as a new value. Being a non-chaining mutator method, list.extend() modifies the subject list in-place and returns nothing.

Arrays

I’ve added this due to the potential confusion which the Abel’s answer above may cause by mixing the discussion of lists, sequences and arrays. Arrays were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays with lists. They are not the same.

From the array docs:

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.


回答 2

append将元素添加到列表。如果要使用新列表扩展列表,则需要使用extend

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

回答 3

Python列表是异构的,即同一列表中的元素可以是任何类型的对象。表达式:c.append(c)将对象添加c到列表中。在这种情况下,它会使列表本身成为列表的成员。

该表达式c += c将两个列表加在一起,并将结果分配给变量c+在列表上定义了重载运算符,以创建一个新列表,其内容是第一个列表中的元素和第二个列表中的元素。

因此,这些实际上只是用于根据设计执行不同操作的不同表达式。

Python lists are heterogeneous that is the elements in the same list can be any type of object. The expression: c.append(c) appends the object c what ever it may be to the list. In the case it makes the list itself a member of the list.

The expression c += c adds two lists together and assigns the result to the variable c. The overloaded + operator is defined on lists to create a new list whose contents are the elements in the first list and the elements in the second list.

So these are really just different expressions used to do different things by design.


回答 4

您正在寻找的方法是extend()。从Python 文档中

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

The method you’re looking for is extend(). From the Python documentation:

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

回答 5

你应该使用extend()

>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

其他信息:追加与扩展

you should use extend()

>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

other info: append vs. extend


回答 6

请参阅文档

list.append(x)

  • 在列表末尾添加一个项目;等效于a [len(a):] = [x]。

list.extend(L)-通过添加给定列表中的所有项目来扩展列表;等效于a [len(a):] =L。

c.append(c)将c 作为元素 “附加”到自身。由于列表是引用类型,因此将创建递归数据结构。

c += c等价于extend(c),将c的元素附加到c。

See the documentation:

list.append(x)

  • Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L) – Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

c.append(c) “appends” c to itself as an element. Since a list is a reference type, this creates a recursive data structure.

c += c is equivalent to extend(c), which appends the elements of c to c.