目录
使用运算符“+”,可以使用"+"运算符将两个列表直接相加,生成一个新的列表。
代码如下:
- #使用运算符“+”
- list1 = [1, 2, 3, 4, 5]
- list2 = [11, 12, 13, 14, 15]
- new_list = list1 + list2
- print("合并后的列表为:", new_list)
使用extend()方法:使用extend()方法将第二个列表的元素逐个添加到第一个列表中。
代码如下:
- #使用extend()
- list1 = [1, 2, 3, 4, 5]
- list2 = [11, 12, 13, 14, 15]
- list1.extend(list2)
- new_list = list1
- print("合并后的列表为:", new_list)
使用append()方法:可以使用循环遍历第二个列表的元素,并使用append()方法将其逐个添加到第一个列表后面。
代码如下:
- #使用append()
- list1 = [1, 2, 3, 4, 5]
- list2 = [11, 12, 13, 14, 15]
-
- for i in list2:
- list1.append(i)
- new_list = list1
- print("合并后的列表为:", new_list)