python 判断两个集合是否存在交集
时间: 2024-01-18 09:49:42 浏览: 63
可以使用 set 的 intersection 方法来判断两个集合是否存在交集,如果交集为空集,则返回 False,否则返回 True。具体实现如下:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
if set1.intersection(set2):
print("Two sets have common elements")
else:
print("Two sets are disjoint")
```
输出结果为:
```
Two sets have common elements
```
相关问题
python求两个集合的交集
你可以使用 & 运算符或 intersection() 方法来求两个集合的交集,如下所示:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 使用 & 运算符求交集
intersection = set1 & set2
print(intersection) # {4, 5}
# 使用 intersection() 方法求交集
intersection = set1.intersection(set2)
print(intersection) # {4, 5}
```
以上代码中,我们创建了两个集合 set1 和 set2,然后使用 & 运算符和 intersection() 方法求它们的交集。最后打印输出交集的结果。
Python计算两个集合的交集并集差集
假设有两个集合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}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)