Python中如何连接两个列表

Python中如何连接两个列表

技术背景

在Python编程中,经常会遇到需要将两个或多个列表连接成一个列表的情况。Python提供了多种方法来实现列表的连接,不同的方法在性能、语法和适用场景上有所不同。

实现步骤

1. 使用 + 运算符

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

这种方法会创建一个新的列表,包含原列表的浅拷贝。

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
listone = [1, 2, 3]
listtwo = [4, 5, 6]
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)
print(mergedlist)

3. 使用 [*l1, *l2] 语法(Python 3.5+)

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

这种方法也创建一个新列表,并且可以处理任何可迭代对象。

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)

如果需要将结果转换为列表,可以使用 list(itertools.chain(listone, listtwo))

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
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# + 运算符
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo

# list.extend()
listone = [1, 2, 3]
listtwo = [4, 5, 6]
listone.extend(listtwo)

# [*l1, *l2]
l1 = [1, 2, 3]
l2 = [4, 5, 6]
joined_list = [*l1, *l2]

# itertools.chain()
import itertools
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joined_list = list(itertools.chain(listone, listtwo))

# 列表推导式
list_one = [1, 2, 3]
list_two = [4, 5, 6]
joined_list = [item for list_ in [list_one, list_two] for item in list_]

最佳实践

  • 少量列表连接:对于少量列表的连接,使用 + 运算符或 [*l1, *l2] 语法(Python 3.5+)是最简单和直观的方法。
  • 大量列表连接:当需要连接大量列表时,使用 itertools.chain()itertools.chain.from_iterable() 可以提高性能,因为它们不会创建中间列表。
  • 需要唯一值:如果需要连接后的列表包含唯一值,可以使用 list(set(listone + listtwo))

常见问题

1. 使用 sum() 连接列表的问题

1
2
list_of_lists = [[1, 2, 3], [4, 5, 6]]
result = sum(list_of_lists, [])

这种方法虽然简洁,但性能较差,因为 sum 是按对进行连接的,对于大列表会导致二次操作。

2. 直接使用 list.__add__ 的问题

不建议直接使用 list.__add__ 方法,应使用 + 运算符,因为 Python 对运算符有更复杂的语义处理。

3. 使用 set 去重的问题

使用 set 会丢失列表的顺序,如果需要保留顺序,不能使用这种方法。

4. appendextend 的性能差异

for i in b: a.append(i)a.extend(b) 更冗长且性能更差,因为 append 每次添加元素时可能需要重新分配内存。


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