如何在不修改任何一个列表的情况下获取Python中两个列表的串联? [重复]

本文探讨了在Python中连接多个列表的不同方法,包括使用list.extend、reduce(operator.add)、sum函数和简单的加号运算。这些方法均能在不修改原始列表的前提下,生成新的连接列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How can I get the concatenation of two lists in Python without modifying either one? [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

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 . 这给出了一个新列表,它是list1list2的串联。


#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. 列表是可变序列,所以我想通过扩展或追加来修改原始列表是有意义的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值