写一个两个集合求交集的
时间: 2024-05-09 15:18:46 浏览: 11
Python程序:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
intersection = set1.intersection(set2)
print(intersection)
```
输出:
```
{3, 4, 5}
```
解释:
首先定义了两个集合,set1和set2。然后使用intersection方法求它们的交集,并将结果存储在变量intersection中。最后打印出intersection的值。
相关问题
Java写写一个两个集合求交集的
代码示例:
```java
import java.util.*;
public class Intersection {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Set 1: " + set1);
System.out.println("Set 2: " + set2);
System.out.println("Intersection: " + intersection);
}
}
```
输出结果:
```
Set 1: [1, 2, 3, 4, 5]
Set 2: [3, 4, 5, 6, 7]
Intersection: [3, 4, 5]
```
说明:
1. 创建两个 Set 对象 set1 和 set2,分别初始化为包含一些整数的 HashSet 对象。
2. 使用 retainAll() 方法获取两个集合的交集,并将结果保存到一个新的 HashSet 对象 intersection 中。
3. 输出集合 set1、set2 和 intersection 的元素。
写一个求集合交集和并集的代码
假设有两个集合 A 和 B,可以用 Python 语言求它们的交集和并集。
求交集的代码如下:
```python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
intersection = A & B # 使用 & 运算符求交集
print("A 和 B 的交集为:", intersection)
```
输出结果为:
```
A 和 B 的交集为: {3, 4}
```
求并集的代码如下:
```python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
union = A | B # 使用 | 运算符求并集
print("A 和 B 的并集为:", union)
```
输出结果为:
```
A 和 B 的并集为: {1, 2, 3, 4, 5, 6}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)