python中两个列表合并
时间: 2023-09-20 19:06:15 浏览: 67
### 回答1:
可以使用extend()方法将一个列表添加到另一个列表的末尾,或使用"+"运算符将两个列表合并成一个新列表。例如:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # 输出 [1, 2, 3, 4, 5, 6]
或者:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3) # 输出 [1, 2, 3, 4, 5, 6]
### 回答2:
在Python中,我们可以使用 "+" 运算符将两个列表合并为一个新的列表。
例如,假设有两个列表:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
```
要将这两个列表合并为一个新的列表,可以使用如下代码:
```
new_list = list1 + list2
```
执行上述代码后,`new_list` 将会成为一个包含所有元素的新列表:
```
new_list = [1, 2, 3, 4, 5, 6]
```
除了使用 "+" 运算符之外,我们还可以使用 extend() 方法将一个列表的元素添加到另一个列表中。这种方法可以实现与 "+" 运算符相同的功能。
例如,假设有两个列表:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
```
要将 `list2` 的元素添加到 `list1` 中,可以使用如下代码:
```
list1.extend(list2)
```
执行上述代码后,`list1` 将包含来自 `list2` 的元素:
```
list1 = [1, 2, 3, 4, 5, 6]
```
### 回答3:
Python中可以使用"+"操作符将两个列表合并成一个新的列表。例如:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)
```
输出结果为:[1, 2, 3, 4, 5, 6]
除了使用"+"操作符,还可以使用extend()方法将一个列表的元素逐一添加到另一个列表中。例如:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
```
输出结果也是:[1, 2, 3, 4, 5, 6]
其中,"+"操作符创建了一个新的列表,而extend()方法是在原来的列表上进行操作。
如果想要在原来的列表上合并两个列表,也可以使用list1 += list2。例如:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1 += list2
print(list1)
```
输出结果同样为:[1, 2, 3, 4, 5, 6]
综上所述,Python中可以使用"+"操作符、extend()方法或者"+="操作符将两个列表合并成一个新的列表或者在原来的列表上合并。