python合并两个列表
时间: 2023-07-11 16:46:09 浏览: 58
可以使用 "+" 运算符来合并两个列表,例如:
```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]
```
相关问题
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]`。