本文翻译自:How can I get the concatenation of two lists in Python without modifying either one? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- How do I concatenate two lists in Python? 如何在Python中连接两个列表? 25 answers 25个答案
In Python, the only way I can find to concatenate two lists is list.extend
, which modifies the first list. 在Python中,我可以找到连接两个列表的唯一方法是list.extend
,它修改了第一个列表。 Is there any concatenation function that returns its result without modifying its arguments? 是否有任何串联函数返回其结果而不修改其参数?
#1楼
参考:https://stackoom.com/question/IE4n/如何在不修改任何一个列表的情况下获取Python中两个列表的串联-重复
#2楼
And if you have more than two lists to concatenate: 如果你有两个以上的列表要连接:
import operator
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, eg, *args
. 它实际上并不会在任何时候保存你(中间列表仍然是创建的)但是如果你有一个可变数量的列表要展平,那就太好了,例如*args
。
#3楼
You can also use sum
, if you give it a start
argument: 如果你给它一个start
参数,你也可以使用sum
:
>>> 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]
#4楼
Yes: list1+list2
. 是: list1+list2
。 This gives a new list that is the concatenation of list1
and list2
. 这给出了一个新列表,它是list1
和list2
的串联。
#5楼
concatenated_list = list_1 + list_2
#6楼
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. 列表是可变序列,所以我想通过扩展或追加来修改原始列表是有意义的。