简体   繁体   English

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

[英]Python append() vs. + operator on lists, why do these give different results?

Why do these two operations ( append() resp. + ) give different results?为什么这两个操作( 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, [...]]
>>> 

In the last case there's actually an infinite recursion.在最后一种情况下,实际上是无限递归。 c[-1] and c are the same. c[-1]c是一样的。 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). array.append操作将数组(或任何对象)插入到原始数组的末尾,这会导致在该位置引用 self (因此是无限递归)。

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.然而, append 方法确实按照您的要求执行:将对象(数组或任何其他对象)添加到右侧,而不是获取其元素。

An alternative另一种选择

Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well).如果您想使用与 + 运算符类似的函数,请使用extend() (正如其他人在此处显示的那样)。 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.为了好玩,来一段历史:1993 年 2 月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 . list.append()方法是list上的一个mutator ,它将其单个object参数(在您的特定示例中为 list c )附加到主题list In your example this results in c appending a reference to itself (hence the infinite recursion).在您的示例中,这会导致c附加对自身的引用(因此是无限递归)。

An alternative to '+' concatenation '+' 连接的替代方法

The list.extend() method is also a mutator method which concatenates its sequence argument with the subject list . list.extend()方法也是一个 mutator 方法,它将其sequence参数与主题list Specifically, it appends each of the elements of sequence in iteration order.具体来说,它按迭代顺序附加sequence每个元素。

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.作为一个非链式mutator方法, list.extend()修改主题列表并且不返回任何内容。

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.我之所以添加这个,是因为上面 Abel 的回答可能会因混合列表、序列和数组的讨论而引起潜在的混乱。 Arrays were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types.在序列和列表之后, Arrays被添加到 Python 中,作为一种更有效的存储整数数据类型数组的方式。 Do not confuse arrays with lists .不要将arrayslists混淆。 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.类型是在对象创建时使用类型代码指定的,类型代码是单个字符。

append is appending an element to a list. append是将一个元素追加到一个列表中。 if you want to extend the list with the new list you need to use extend .如果要使用新列表扩展列表,则需要使用extend

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

Python lists are heterogeneous that is the elements in the same list can be any type of object. Python 列表是异构的,即同一列表中的元素可以是任何类型的对象。 The expression: c.append(c) appends the object c what ever it may be to the list.表达式: c.append(c)将对象c附加到列表中。 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 .表达式c += c将两个列表相加,并将结果分配给变量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.所以这些实际上只是不同的表达方式,用于按照设计做不同的事情。

The method you're looking for is extend() .您正在寻找的方法是extend() From the Python documentation :从 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).

you should use extend()你应该使用扩展()

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

other info: append vs. extend其他信息: 附加与扩展

See the documentation :请参阅文档

list.append(x) list.append(x)

  • Add an item to the end of the list;在列表末尾添加一个项目; equivalent to a[len(a):] = [x].等价于 a[len(a):] = [x]。

list.extend(L) - Extend the list by appending all the items in the given list; list.extend(L) - 通过附加给定列表中的所有项目来扩展列表; equivalent to a[len(a):] = L.相当于 a[len(a):] = L。

c.append(c) "appends" c to itself as an element . c.append(c)将 c作为元素“附加”到自身。 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. c += c等效于extend(c) ,它将c 的元素附加到 c。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 R 和 Python FFT 给出不同的结果? - Why do the R and Python FFT give different results? 当我想在 Python 中将字典添加到列表中时,为什么 append() 和 += 会给出不同的结果? - Why does append() and += give different results when I want to add a dictionary into a list in Python? 为什么追加后Pycharm调试器和python运行程序会给出两个不同的结果? - Why does the Pycharm debugger and the python running program give two different results after append? last() 和 [] 运算符给出不同的结果 - last() and [] operator give different results 使用append方法和+运算符追加列表会在Python中产生不同的结果吗? - Appending to list using append method and + operator produces different results in Python? OpenCV MergeMertens在Python Vs中给出不同的结果。 C ++ - OpenCV MergeMertens gives different results in Python Vs. C++ R中的lm与Python中的statsmodel OLS的结果不同 - Different results from lm in R vs. statsmodel OLS in Python 在python解释器和脚本文件中运行时的结果不同 - Different results when running in python interpreter vs. script file 不同的结果 statsmodels(python) 与 R 自相关 - Different results statsmodels(python) vs. R autocorrelation 日期差异:Excel 与 Python 中的不同结果 - Date difference: different results in Excel vs. Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM