如何在 Python 中连接两个列表而不修改其中任何一个?
在Python中,我能找到连接两个列表的唯一方法是list.extend,它修改第一个列表。是否有任何串联函数可以返回其结果而不修改其参数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是:
list1 + list2
。这给出了一个新列表,它是list1
和list2
的串联。Yes:
list1 + list2
. This gives a new list that is the concatenation oflist1
andlist2
.最简单的方法就是使用 + 运算符,它返回列表的串联:
concat = first_list + secondary_list
此方法的一个缺点是现在内存增加了一倍正在使用。对于非常大的列表,取决于创建后您将如何使用它,
itertools.chain
可能是您最好的选择:这会为组合列表中的项目创建一个生成器,其优点是不需要创建新列表,但您仍然可以使用
c
就好像它是两个列表的串联:如果您的列表很大并且效率是一个问题,那么这个方法和来自
itertools
模块的其他方法非常容易了解。请注意,此示例使用了
c
中的项目,因此您需要重新初始化它,然后才能重用它。当然,您可以仅使用list(c)
创建完整列表,但这将在内存中创建一个新列表。The simplest method is just to use the
+
operator, which returns the concatenation of the lists: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.chain
might be your best bet: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
c
as though it were the concatenation of the two lists:If your lists are large and efficiency is a concern then this and other methods from the
itertools
module are very handy to know.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 uselist(c)
to create the full list, but that will create a new list in memory.concatenated_list = list_1 + list_2
concatenated_list = list_1 + list_2
如果您给它一个
start
参数,您还可以使用sum
:这通常适用于具有
+
运算符 的任何内容:字符串例外:
You can also use
sum
, if you give it astart
argument:This works in general for anything that has the
+
operator:With the notable exception of strings:
您始终可以创建一个新列表,这是添加两个列表的结果。
列表是可变序列,因此我认为通过扩展或追加来修改原始列表是有意义的。
you could always create a new list which is a result of adding two lists.
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
如果您有两个以上的列表需要连接:
它实际上并不会节省您任何时间(仍然会创建中间列表),但如果您有可变数量的列表需要展平,例如,*args。
And if you have more than two lists to concatenate:
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
.只是想让您知道:
当您编写
list1 + list2
时,您正在调用list1
的__add__
方法,该方法返回一个新列表。通过这种方式,您还可以通过将__add__
方法添加到您的个人类来处理myobject + list1
。Just to let you know:
When you write
list1 + list2
, you are calling the__add__
method oflist1
, which returns a new list. in this way you can also deal withmyobject + list1
by adding the__add__
method to your personal class.