python合并两个列表
时间: 2023-09-12 12:13:24 浏览: 44
你可以使用 "+" 运算符将两个列表合并为一个新的列表,也可以使用 extend() 方法将一个列表添加到另一个列表的末尾。以下是两个示例:
使用 "+" 运算符合并两个列表:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)
```
输出:
```
[1, 2, 3, 4, 5, 6]
```
使用 extend() 方法将一个列表添加到另一个列表的末尾:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
```
输出:
```
[1, 2, 3, 4, 5, 6]
```
相关问题
python 合并两个列表并去重
可以使用 set 和 extend 方法合并两个列表并去重:
```python
list1 = [1, 2, 3]
list2 = [2, 3, 4]
result = list(set(list1).union(set(list2)))
print(result) # [1, 2, 3, 4]
```
也可以使用 for 循环和 if 判断来实现:
```python
list1 = [1, 2, 3]
list2 = [2, 3, 4]
result = list1.copy()
for i in list2:
if i not in result:
result.append(i)
print(result) # [1, 2, 3, 4]
```
还可以使用列表推导式来实现:
```python
list1 = [1, 2, 3]
list2 = [2, 3, 4]
result = list(set([i for i in list1] + [j for j in list2]))
print(result) # [1, 2, 3, 4]
```
以上三种方法都可以实现两个列表的合并和去重。
python合并两个列表并去重
可以使用 set 和 union 方法来合并两个列表并去重,示例代码如下:
```python
list1 = [1, 2, 3]
list2 = [2, 3, 4]
result = list(set(list1).union(set(list2)))
print(result)
```
输出结果为:`[1, 2, 3, 4]`。
另外,也可以使用列表推导式和 not in 来实现,示例代码如下:
```python
list1 = [1, 2, 3]
list2 = [2, 3, 4]
result = list1 + [x for x in list2 if x not in list1]
print(result)
```
输出结果为:`[1, 2, 3, 4]`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)