Python中如何连接两个列表

Python中如何连接两个列表

技术背景

在Python编程中,经常会遇到需要将两个列表连接成一个列表的情况。例如,在数据处理、算法实现等场景中,合并列表是一个常见的操作。Python提供了多种方法来实现列表的连接,每种方法都有其特点和适用场景。

实现步骤

1. 使用+运算符

这是最直观的方法,它会创建一个新的列表,包含两个原始列表的所有元素。

1
2
3
4
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
print(joinedlist) # 输出: [1, 2, 3, 4, 5, 6]

2. 使用list.extend()方法

该方法会将一个列表的元素添加到另一个列表的末尾,会修改原列表。

1
2
3
4
listone = [1, 2, 3]
listtwo = [4, 5, 6]
listone.extend(listtwo)
print(listone) # 输出: [1, 2, 3, 4, 5, 6]

如果想保留原列表,可以创建一个新的列表并扩展:

1
2
3
4
5
6
listone = [1, 2, 3]
listtwo = [4, 5, 6]
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)
print(mergedlist) # 输出: [1, 2, 3, 4, 5, 6]

3. Python >= 3.5 使用[*l1, *l2]

通过*进行解包操作,将两个可迭代对象合并到一个新列表中。

1
2
3
4
l1 = [1, 2, 3]
l2 = [4, 5, 6]
joined_list = [*l1, *l2]
print(joined_list) # 输出: [1, 2, 3, 4, 5, 6]

4. 使用itertools.chain()

该方法创建一个生成器,逐个迭代两个列表的元素,而不需要创建新的列表。

1
2
3
4
5
import itertools
listone = [1, 2, 3]
listtwo = [4, 5, 6]
for item in itertools.chain(listone, listtwo):
print(item) # 依次输出 1, 2, 3, 4, 5, 6

如果需要得到一个列表,可以使用list()将生成器转换为列表:

1
2
3
4
5
import itertools
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = list(itertools.chain(listone, listtwo))
print(joinedlist) # 输出: [1, 2, 3, 4, 5, 6]

5. 使用列表推导式

1
2
3
4
list_one = [1, 2, 3]
list_two = [4, 5, 6]
joined_list = [item for list_ in [list_one, list_two] for item in list_]
print(joined_list) # 输出: [1, 2, 3, 4, 5, 6]

最佳实践

  • 性能考虑:对于少量列表的连接,+运算符和[*l1, *l2]方法简单直观;对于大量列表的连接,itertools.chain()方法性能更好,因为它是基于生成器的,不会一次性占用大量内存。
  • 代码可读性:在大多数情况下,+运算符和list.extend()方法的代码可读性较高,容易理解。
  • 避免使用__add__方法:直接使用list.__add__方法不是一个好的做法,应该使用+运算符或operator.add函数。

常见问题

1. 浅拷贝问题

使用+运算符和[*l1, *l2]方法创建的新列表是原列表元素的浅拷贝。如果原列表中的元素是可变对象,修改新列表中的元素可能会影响原列表。可以使用copy.deepcopy()进行深拷贝。

1
2
3
4
5
6
import copy
listone = [[1], [2]]
listtwo = [[3], [4]]
joinedlist = copy.deepcopy(listone + listtwo)
joinedlist[0][0] = 10
print(listone) # 输出: [[1], [2]]

2. 排序合并问题

如果需要将两个有序列表合并成一个有序列表,可以使用heapq.merge()方法。

1
2
3
4
from heapq import merge
a = [1, 2, 4]
b = [2, 4, 6, 7]
print(list(merge(a, b))) # 输出: [1, 2, 2, 4, 4, 6, 7]

3. 去重问题

如果需要合并两个列表并去除重复元素,可以使用set

1
2
3
4
listone = [1, 2, 3]
listtwo = [3, 4, 5]
mergedlist = list(set(listone + listtwo))
print(mergedlist) # 输出: [1, 2, 3, 4, 5](顺序可能不同)

如果需要保留元素的顺序,可以使用collections.OrderedDict(Python 3.6 之前)或dict.fromkeys(Python 3.6 及以后)。

1
2
3
4
listone = [1, 2, 3]
listtwo = [3, 4, 5]
mergedlist = list(dict.fromkeys(listone + listtwo))
print(mergedlist) # 输出: [1, 2, 3, 4, 5]

Python中如何连接两个列表
https://119291.xyz/posts/2025-04-14.python-list-concatenation-guide/
作者
ww
发布于
2025年4月14日
许可协议