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

发布于 2024-08-17 02:55:35 字数 344 浏览 1 评论 0原文

为什么这两个操作会给出不同的结果?

>>> 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 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 infinite recursion. c[-1] and c are the same. Why is it different with the + operation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

彼岸花ソ最美的依靠 2024-08-24 02:55:35

编者注:这个答案混淆了列表< /a> 与 数组 以及 +=+。尽管如此,这些概念足够相似,仍然有用。


解释“为什么”:

+ 操作 添加 数组 元素添加到原始数组中。 array.append< /a> 操作将数组(或任何对象)插入到原始数组的末尾,这会导致在该位置产生对 self 的引用(因此在列表的情况下会无限递归,尽管使用数组,您会收到类型错误)。

此处的区别在于,当您添加数组时,+ 操作会起作用(它与其他数组一样重载,请参阅本章关于序列)通过连接元素。然而,append 方法确实按照您的要求执行:将对象附加到您提供的右侧(数组或任何其他对象),而不是获取其元素。

另一种方法

是使用 extend() 如果您想使用与 + 运算符类似的函数(正如其他人在此处所示的那样)。做相反的事情是不明智的:尝试用 + 运算符模仿列表的 append (请参阅我的 早期链接说明原因)。有关列表的更多信息如下:

列表

[编辑] 一些评论者建议问题是关于列表而不是关于数组。问题已经改变,尽管我应该早点把它包括在内。

上面关于数组的大部分内容也适用于列表:

  • + 运算符将两个列表连接在一起。该运算符将返回一个新的列表对象。
  • List.append 不会将一个列表附加到另一个列表,而是附加一个对象(这里是一个列表 )位于当前列表的末尾。因此,将 c 添加到自身会导致无限递归。
  • 与数组一样,您可以使用 List.extend< /code>添加用另一个列表(或可迭代)扩展列表。这将原位更改您当前的列表,而不是返回一个新列表的+

Editor's note: This answer confuses lists with arrays as well as += with +. Despite that, the concepts are similar enough to still be useful.


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 in your case with lists, though with arrays, you'd receive a type error).

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). More on lists below:

Lists

[edit] Several commenters have suggested that the question is about lists and not about arrays. The question has changed, though I should've included this earlier.

Most of the above about arrays also applies to lists:

  • The + operator concatenates two lists together. The operator will return a new list object.
  • List.append does not append one list with another, but appends a single object (which here is a list) at the end of your current list. Adding c to itself, therefore, leads to infinite recursion.
  • As with arrays, you can use List.extend to add extend a list with another list (or iterable). This will change your current list in situ, as opposed to +, which returns a new list.
一影成城 2024-08-24 02:55:35

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

“+”连接的替代方案

list.extend() 方法也是一个 mutator 方法,它将其可迭代参数与主题 列表。具体来说,它按迭代顺序附加可迭代的每个元素。

旁白

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

数组

我添加了这个,因为上面Abel的答案可能会因混合列表、序列的讨论而造成潜在的混乱和数组。

数组被添加到Python中的序列和列表之后,如下所示存储整型数据类型数组的更有效方法。不要将数组列表混淆。它们不一样。

来自数组文档

数组是序列类型,其行为与列表非常相似,只是其中存储的对象类型受到限制。类型是在对象创建时使用类型代码(单个字符)指定的。

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 iterable argument with the subject list. Specifically, it appends each of the elements of the iterable 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 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.

π浅易 2024-08-24 02:55:35

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]
萌无敌 2024-08-24 02:55:35

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.

喜爱皱眉﹌ 2024-08-24 02:55:35

您正在寻找的方法是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).
深海夜未眠 2024-08-24 02:55:35

你应该使用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

近箐 2024-08-24 02:55:35

请参阅文档

list.append(x)

  • 将一个项目添加到列表末尾;相当于a[len(a):] = [x]。

列表.扩展(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文