在 Python 3 中连接列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14301056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:01:26  来源:igfitidea点击:

Concatenating lists in Python 3

pythonpython-3.x

提问by Ci3

I'm reading Dive into Python 3and at the section of lists, the author states that you can concatenate lists with the "+" operator or calling the extend() method. Are these the same just two different ways to do the operation? Any reason I should be using one or the other?

我正在阅读Dive into Python 3并且在列表部分,作者指出您可以使用“+”运算符连接列表或调用 extend() 方法。这些只是两种不同的操作方式吗?我应该使用其中一个的任何理由?

>>> a_list = a_list + [2.0, 3]
>>> a_list.extend([2.0, 3])  

采纳答案by Blckknght

a_list.extend(b_list)modifies a_listin place. a_list = a_list + b_listcreates a new list, then saves it to the name a_list. Note that a_list += b_listshould be exactly the same as the extendversion.

a_list.extend(b_list)a_list就地修改。a_list = a_list + b_list创建一个新列表,然后将其保存到 name a_list。注意a_list += b_list应该和extend版本完全一样。

Using extendor +=is probably slightly faster, since it doesn't need to create a new object, but if there's another reference to a_listaround, it's value will be changed too (which may or may not be desirable).

使用extendor+=可能稍微快一点,因为它不需要创建一个新对象,但是如果有另一个对a_listaround的引用,它的值也会改变(这可能是也可能不是可取的)。