在Python中,合并列表的方法有多种,以下是几种常见的方法:
1. 使用`+`操作符合并列表:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list_new = list1 + list2
print(list_new) 输出:[1, 2, 3, 4, 5, 6]
2. 使用`extend()`方法合并列表:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) 输出:[1, 2, 3, 4, 5, 6]
3. 使用`*`操作符和解包合并列表:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list_new = [*list1, *list2]
print(list_new) 输出:[1, 2, 3, 4, 5, 6]
4. 使用`itertools.chain()`函数合并列表:
from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list_new = list(chain(list1, list2))
print(list_new) 输出:[1, 2, 3, 4, 5, 6]
5. 使用`reduce()`函数合并列表:
from functools import reduce
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list_new = reduce(lambda x, y: x + y, [list1, list2])
print(list_new) 输出:[1, 2, 3, 4, 5, 6]