如何在 Python 中连接两个列表而不修改其中任何一个?

发布于 2024-10-05 14:50:44 字数 77 浏览 5 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

等往事风中吹 2024-10-12 14:50:44

是:list1 + list2。这给出了一个新列表,它是 list1list2 的串联。

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

固执像三岁 2024-10-12 14:50:44

最简单的方法就是使用 + 运算符,它返回列表的串联:

concat = first_list + secondary_list

此方法的一个缺点是现在内存增加了一倍正在使用。对于非常大的列表,取决于创建后您将如何使用它, itertools.chain 可能是您最好的选择:

>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)

这会为组合列表中的项目创建一个生成器,其优点是不需要创建新列表,但您仍然可以使用c 就好像它是两个列表的串联:

>>> for i in c:
...     print i
1
2
3
4
5
6

如果您的列表很大并且效率是一个问题,那么这个方法和来自 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:

>>> 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 c as though it were the concatenation of the two lists:

>>> 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 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 use list(c) to create the full list, but that will create a new list in memory.

橘和柠 2024-10-12 14:50:44

concatenated_list = list_1 + list_2

concatenated_list = list_1 + list_2

烟酒忠诚 2024-10-12 14:50:44

如果您给它一个 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]

这通常适用于具有 + 运算

>>> 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

符 的任何内容:字符串例外:

>>> 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]

You can also use sum, if you give it a start argument:

>>> 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]
明媚殇 2024-10-12 14:50:44

您始终可以创建一个新列表,这是添加两个列表的结果。

>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]

列表是可变序列,因此我认为通过扩展或追加来修改原始列表是有意义的。

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.

一抹淡然 2024-10-12 14:50:44

如果您有两个以上的列表需要连接:

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)

它实际上并不会节省您任何时间(仍然会创建中间列表),但如果您有可变数量的列表需要展平,例如,*args。

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.

等往事风中吹 2024-10-12 14:50:44

只是想让您知道:

当您编写 list1 + list2 时,您正在调用 list1__add__ 方法,该方法返回一个新列表。通过这种方式,您还可以通过将 __add__ 方法添加到您的个人类来处理 myobject + list1

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 + list1 by adding the __add__ method to your personal class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文