如何在不修改任何一个的情况下在 Python 中连接两个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4344017/
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
How can I get the concatenation of two lists in Python without modifying either one?
提问by Ryan C. Thompson
In Python, the only way I can find to concatenate two lists is list.extend, which modifies the first list. Is there any concatenation function that returns its result without modifying its arguments?
在 Python 中,我能找到连接两个列表的唯一方法是list.extend,它修改第一个列表。是否有任何连接函数可以在不修改其参数的情况下返回其结果?
采纳答案by NPE
Yes: list1 + list2. This gives a new list that is the concatenation of list1and list2.
是:list1 + list2。这给出了一个由list1and串联而成的新列表list2。
回答by Johan Kotlinski
concatenated_list = list_1 + list_2
concatenated_list = list_1 + list_2
回答by pyfunc
you could always create a new list which is a result of adding two lists.
您总是可以创建一个新列表,这是添加两个列表的结果。
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
列表是可变序列,所以我想通过扩展或附加来修改原始列表是有意义的。
回答by Scott Griffiths
The simplest method is just to use the +operator, which returns the concatenation of the lists:
最简单的方法是使用+运算符,它返回列表的串联:
concat = first_list + second_list
concat = first_list + second_list
One disadvantage of this method is that twice the memory is now being used . For very large lists, depending on how you're going to use it once it's created, itertools.chainmight be your best bet:
这种方法的一个缺点是现在使用了两倍的内存。对于非常大的列表,根据您在创建后将如何使用它,itertools.chain可能是您最好的选择:
>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)
This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use cas though it were the concatenation of the two lists:
这为组合列表中的项目创建了一个生成器,其优点是不需要创建新列表,但您仍然可以使用c它,就好像它是两个列表的串联一样:
>>> for i in c:
... print i
1
2
3
4
5
6
If your lists are large and efficiency is a concern then this and other methods from the itertoolsmodule are very handy to know.
如果您的列表很大并且需要考虑效率,那么itertools了解模块中的此方法和其他方法非常方便。
Note that this example uses up the items in c, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c)to create the full list, but that will create a new list in memory.
请注意,此示例使用了 中的项目c,因此您需要重新初始化它,然后才能重用它。当然,您可以只使用list(c)来创建完整列表,但这将在内存中创建一个新列表。
回答by Ant
Just to let you know:
只是让你知道:
When you write list1 + list2, you are calling the __add__method of list1, which returns a new list. in this way you can also deal with myobject + list1by adding the __add__method to your personal class.
当您编写 时list1 + list2,您正在调用 的__add__方法list1,该方法返回一个新列表。通过这种方式,您还可以myobject + list1通过将__add__方法添加到您的个人类来处理。
回答by Jake Biesinger
And if you have more than two lists to concatenate:
如果您有两个以上的列表要连接:
import operator
from functools import reduce # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])
# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)
It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.
它实际上并没有为您节省任何时间(仍然会创建中间列表),但是如果您有可变数量的列表要展平,例如*args.
回答by Thomas Ahle
You can also use sum, if you give it a startargument:
你也可以使用sum, 如果你给它一个start参数:
>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]
This works in general for anything that has the +operator:
这通常适用于具有+运算符的任何内容:
>>> sum([(1,2), (1,), ()], ())
(1, 2, 1)
>>> sum([Counter('123'), Counter('234'), Counter('345')], Counter())
Counter({'1':1, '2':2, '3':3, '4':2, '5':1})
>>> sum([True, True, False], False)
2
With the notable exception of strings:
除了字符串的显着例外:
>>> sum(['123', '345', '567'], '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

