Python计算两个集合的交集并集差集
时间: 2024-01-01 13:17:43 浏览: 37
假设有两个集合A和B,可以用Python的set类型表示它们。交集、并集、差集的计算可以使用set类型提供的交集运算符&、并集运算符|、差集运算符-,具体实现如下:
```python
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
# 计算交集
intersection = A & B
print("交集:", intersection)
# 计算并集
union = A | B
print("并集:", union)
# 计算差集
difference = A - B
print("差集:", difference)
```
上述代码输出结果:
```
交集: {3, 4}
并集: {1, 2, 3, 4, 5, 6}
差集: {1, 2}
```
相关问题
Python交集。并集差集补集
Python中,可以使用集合(set)来进行交集、并集、差集和补集的操作。
1. 交集:两个集合中共同存在的元素构成的新集合。可以使用`&`算符或者`intersection()`方法来实现。
示例代码:
```
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1 & set2
# 或者使用 intersection() 方法
# intersection_set = set1.intersection(set2)
print(intersection_set) # 输出: {2, 3}
```
2. 并集:两个集合中所有的元素构成的新集合。可以使用`|`运算符或者`union()`方法来实现。
示例代码:
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1 | set2
# 或者使用 union() 方法
# union_set = set1.union(set2)
print(union_set) # 输出: {1, 2, 3, 4}
```
3. 差集:第一个集合中存在,而第二个集合中不存在的元素构成的新集合。可以使用`-`运算符或者`difference()`方法来实现。
示例代码:
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference_set = set1 - set2
# 或者使用 difference() 方法
# difference_set = set1.difference(set2)
print(difference_set) # 输出: {1}
```
4. 补集:在全集中存在,但是不在指定集合中的元素构成的新集合。可以使用`^`运算符或者`symmetric_difference()`方法来实现。
示例代码:
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
complement_set = set1 ^ set2
# 或者使用 symmetric_difference() 方法
# complement_set = set1.symmetric_difference(set2)
print(complement_set) # 输出: {1, 4}
```
python集合的对称差集(并集-交集)
Python中的集合是一种无序且不重复的数据构。对称差集是指两个集合的并集减去交集的部分。在Python中,可以使用集合的操作符或方法来计算对称差集。
使用操作符:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
symmetric_difference = set1 ^ set2
print(symmetric_difference)
```
输出:
```
{1, 2, 5, 6}
```
使用方法:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
symmetric_difference = set1.symmetric_difference(set2)
print(symmetric_difference)
```
输出:
```
{1, 2, 5, 6}
```