python 合并函数
时间: 2025-01-12 17:55:07 浏览: 38
在Python中,合并函数通常指的是将两个或多个数据结构(如列表、字典等)合并成一个。Python提供了多种方法来合并数据结构,以下是一些常见的合并函数:
1. **列表合并**:
- 使用 `+` 运算符:
```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]
```
2. **字典合并**:
- 使用 `update()` 方法:
```python
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # 输出: {'a': 1, 'b': 3, 'c': 4}
```
- 使用字典解包(Python 3.5+):
```python
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # 输出: {'a': 1, 'b': 3, 'c': 4}
```
3. **集合合并**:
- 使用 `|` 运算符:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
merged_set = set1 | set2
print(merged_set) # 输出: {1, 2, 3, 4, 5}
```
- 使用 `union()` 方法:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
merged_set = set1.union(set2)
print(merged_set) # 输出: {1, 2, 3, 4, 5}
```
这些方法可以根据具体需求选择使用,确保在合并时注意数据结构的特性和可能的冲突。
阅读全文
相关推荐


















